Flask|Jinjia2|Javascript: Passing Flask template variable into Javascript

What is the best way to pass a variable from a Flask template into the Javascript file? Here is my code

I have a simple view in my webapp:

@webapp.route('/bars')
def plot_d3_bars():
  return render_template("bars.html", calendarMap = calendarMap)

I have a templated HTML file that looks like this:

{% extends "base.html" %}

{% block title %} Bar View {% endblock %}

{% block content %}

{% with calendarMap=calendarMap %}
    {% include "buttons.html" %}
{% endwith %}

<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script src="/static/css/d3.tip.v0.6.3.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

<!-- Custom codes for d3 plotting -->
<link href="/static/css/bars.css" rel="stylesheet">
<script> var calendarMap = {{ calendarMap|tojson }}; </script>
<script src="/static/bars.js"></script>

{% endblock %}

Previous answers told me that I could just jsonify the variable into a JSON object and I'll be able to use it. However, I want to use calendarMap inside of bars.js? but I am running into some scoping problems (i.e. bars.js doesn't recognized this calendarMap), what should I do instead?

Answers:

Answer

Well, maybe it is too late, but here we go.

When you use a JavaScript code embedded in HTML code, this script will be rendered together with HTML. So any variable referenced in JavaScript, as a Flask variable, will be available in the page rendered.

When you use an external JavaScript file linked in HTML code, its code already exists, before the HTML be rendered. In some cases, I may say most of them, you aren't the owner of this file. So any variable referenced in JS file will not be rendered.

You may put this variable in HTML, via JS code, and consume this data with functions from foreign JS file.

Or you can render this JS file, before render the template, and use it. But I strongly recomend not to use this approach.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.