How to change document template in Bokeh server embedded in Flask?

I am using the example with the whole directory structure as found in the git repository as a test ground to use a custom Jinja template for document rendering. Tried multiple approached, but none with success.

First I added into the templates directory an ‘index.html’ file as described in documentation.

Next idea was to add the template file as parameter to the Server call

@app.route('/', methods=['GET'])
def bkapp_page():
    script = server_document('http://localhost:5006/')
    return render_template("embed.html", script=script, template="Flask")

def bk_worker():
    server = Server({'/': bkapp}, io_loop=IOLoop(), allow_websocket_origin=["localhost:8000"], index='index.html)

Finally I tried to change the document’s template member variable directly using the following code snippet as bkapp() function:

from jinja2 import Environment
def bkapp(doc):
    my_template = Environment().from_string("""
            {% extends base %}
            {% block contents %}
                <p> Hello {{ user_id }}, AKA '{{ last_name }}, {{ first_name }}'! </p>
            {% endblock %}
    doc.template = my_template
    doc.template_variables["user_id"] = 23
    doc.template_variables.update(first_name="Mary", last_name="Jones")

When debugging, doc.template.filename in bkapp() always shows the default file
‘/home/fugu/bin/loc_py/lib/python3.11/site-packages/bokeh/core/_templates/file.html’ or in the last case nothing is displayed.

What is a working strategy to use a custom template for rendering the document?

Doesn’t really help your exact problem, but If you only need to render Bokeh elements in a custom HTML template, you could skip Flask entirely, as done in bokeh/examples/server/app/faces at branch-3.2 · bokeh/bokeh · GitHub

Thanks for the suggestion. In my case this is not an option since the flask/bokeh tandem is part of a bigger framework.
However, after some debugging I came to the conclusion that changing the document template for an embedded bokeh server is not working. The server_document() call returns a script using a XMLHttpRequest to get the data from the bokeh server. On bokeh server side this request is handled by some AutoloadJsHandler object. This handler ignores all template file configurations and the template member in the Document object. It used its own template to generate the output that is send to web browser and this template cannot be changed.
At least this is how I understood after stepping through the code. But my knowledge in web technology is very limited.

My theoretical solution is to use the bokeh server to render “atomic” pieces. The flask side will do all the bokeh server calls and stitch the individual pieces together with an jinja template.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.