Flavio Barros Flavio Barros - 1 year ago 115
Javascript Question

Integrate chessbord.js with Flask

I'm working with Flask and I'm having problems using chessboard.js with it.

My static folder is something like this:


where I put the files for chessboard.js.

My template:

{% extends "base_templates/page_base.html" %} {# base_templates/page_base.html extends base_templates/base.html #}

{% block main %}
<h1>Home page</h1>

<p>This page is accessible to any user.</p>

{% if not current_user.is_authenticated() %}
To view the Member page, you must
<a href="{{ url_for('user.login') }}">Sign in</a> or
<a href="{{ url_for('user.register') }}">Register</a>.
{% endif %}

<p>The code:</p>
<p>ChessBoard initializes to an empty board with no second argument.

<!-- Here the chessboard code: start example HTML --->
<div id="board" style="width: 400px"></div>
<!-- end example HTML --->

<script type="text/javascript" src='/static/js/json3.min.js'></script>
<script type="text/javascript" src='/static/js/jquery.min.js'></script>
<script type="text/javascript" src='/static/js/chessboard.js'></script>

var init = function() {

//--- start example JS ---
var board = new ChessBoard('board');
//--- end example JS ---

}; // end init()
{% endblock %}

The javascript can't find the images to show the board. It tries to find the images at /img/ not at /static/img/. How can I fix this?

Answer Source

On line 445 of chessboard-0.3.0.js, it says

cfg.pieceTheme = 'img/chesspieces/wikipedia/{piece}.png';

If you change it to:

cfg.pieceTheme = '/static/img/chesspieces/wikipedia/{piece}.png';

does that fix your problem? You might have to play around with the exact path to reflect your complete directory structure (or use a relative path) but this is the place where it needs to be changed.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download