Search code examples
javascriptpythonflaskchessboard.js

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:

/static/
    /css/
    /img/
    /js

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() %}
<p>
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>.
</p>
{% endif %}

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

<!-- 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>
<script>

var init = function() {

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

}; // end init()
$(document).ready(init);
</script>
{% 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?


Solution

  • 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.