Skip to content

My way to pass data in Jinja template

Jinja template variables is just a print statement.

{{ foo }} 
== print(foo)

It’s important to know that the outer double-curly braces are not part of the variable, but the print statement.

Most people pass a dict and take an attribute/item of it for a replacement.
For example:

# flask app.py
data = {'k1': 1, 'k2': 'v2', 'k3': None}
@app.route("/a", methods=["GET", "POST"])
def a():
    return render_template("a.html", data=data)

# a.html
<body>
    <script>
        console.log({{ data.k1 | safe }}); // 1
        // Undefined error
        // because it is rendered as: console.log(None);
        console.log({{ data.k3 | safe }}); 
    </script>
</body>

I pass a json string directly and use it as a json object in javascript.
Note that:
- The None is converted to natural null in js.

# flask app.py
data = {'k1': 1, 'k2': 'v2', 'k3': None}
@app.route("/a", methods=["GET", "POST"])
def a():
    return render_template("a.html", data=json.dumps(data))

# a.html
<body>
    <script>  
        var values = {{ data | safe }};
        console.log(values); // {k1: 1, k2: 'v2', k3: null}
        console.log(values.k1); // 1
    </script>
</body>