Flexibility and compatibility with html templating inside Dash layout

disclaimer: I am little experienced as a web developer, and only recently have started on a dynamic dashboard project

I am looking to make a highly customized table (dynamic svg elements in table and hover sparklines), and feel the best way to do this is using jinja2 as it seems more flexible. I would like to do this within a dash_app framework to take advantage of callbacks and layout, but I cannot serve my dash_app with flask and also render a Jinja template within my flask app. As far as I am concerned, this is not possible or the way to go as Dash appears to be standalone, but unfortunately is not as flexible (w.r.t. tables) as I want.

My question is: Is there a way (maybe even a hack) to get a jinja table rendered inside a html.Div element? Is there even a way to get simple html rendered inside a html.Div element? This is the only semi-compatible way I could see working out. Thank you!

There is not a way to mix and match jinja templating with Dash right now. You have to use the dash_html_components library. There has been some discussion around adding a RawHTML component to Dash here: https://github.com/plotly/dash/issues/44

Here’s what I did to build a Dash template from an existing Flask, Jinja template.

In case you’re wondering, I built a hybrid web app that uses both Flask and Dash.

First extend your “base.html” template into a Dash-specific template (e.g. “base_dash.html”), using HTML comments for the things Dash needs to replace (e.g. {%metas%} or {%app_entry%}:

{% extends "base.html" %}

{% block head %}
  <!-- metas -->
  <title>
    <!-- title -->
  </title>
  <!-- favicon -->
  <!-- css -->
{% endblock %}

{% block body %}
  <!-- app_entry -->

<footer>
  <!-- config -->
  <!-- scripts -->
  <!-- renderer -->
</footer>
{% endblock %}

Back in Python, set up the Dash app:

    dashapp = dash.Dash()

    # FYI, you need both an app context and a request context to use url_for() in the Jinja2 templates
    with app.app_context(), app.test_request_context():
        layout_dash = pathlib.Path(get_root_path(__name__)).joinpath("templates").joinpath("base_dash.html")

        with open(layout_dash, "r") as f:
            html_body = render_template_string(f.read())

        comments_to_replace = ("metas", "title", "favicon", "css", "app_entry", "config", "scripts", "renderer")
        for comment in comments_to_replace:
            html_body = html_body.replace(f"<!-- {comment} -->", "{%" + comment + "%}")

        dashapp.index_string = html_body
1 Like