20

I have this in my flask views.py

    def showpage():
      ...
      test = [1,2,3,4,5,6]
      return render_template("sample.html",test=test)

I have this in my sample .html

    <script> var counts = {{test}}; </script>

This gives me a empty counts variable. How can I get the counts same as the test list in python?

3
  • Can you show rendered source with your template? Commented Apr 13, 2014 at 4:34
  • the thing is it doesn't render. if i use the solution below it says unexpected end of input at the JSON.parse Commented Apr 13, 2014 at 4:56
  • Is nothing empty string or <script> var counts = ; </script> or something else? Commented Apr 13, 2014 at 5:09

5 Answers 5

28
  1. When you insert variable to template {{ test }} it take object representation. For list of int [1,2,3,4,5,6] it will be rendered as [1, 2, 3, 4, 5, 6], so it is valid javascript array, but this method not safe complex objects without javascript-like representation, for example, test = [1,2,3,4,5,any] will rendered as [1, 2, 3, 4, 5, &lt;built-in function any&gt;], however this is just example and will never work.

  2. To implicitly cast to javascript object in flask exist tojson filter:

    <script> var counts = {{ test|tojson }}; </script>
    

    So if the object is JSON serializable, then all will be rendered, otherwise the template engine will raise an exception.

  3. You also can send javascript code to your template:

    from flask import json
    return render_template("sample.html",test=json.dumps(test))
    

    but it is not a good approach and it's better use tojson filter that is also HTML markup safe.

  4. I prefer to not mix any javascript code within templates and split templates, javascript and javascript data with ajax. If this approach is hard I would prefer to use tojson filter.

Sign up to request clarification or add additional context in comments.

1 Comment

The tojson filter produces a HTML safe version of the value, json.dumps() does not. Always use |tojson in the template, not json.dumps(), when producing JavaScript values.
8

You can also use

{{ test|safe }} 

or

{{ test|tojson|safe }}

The safe filter is to be used within script tags.

Comments

7

You use json.dumps in the flask view and JSON.parse in the javascript code.

In the python view:

def showpage():
    ...
    test = [1,2,3,4,5,6]
    test = json.dumps(test)
    return render_template("sample.html",test=test)

In the JavaScript code:

<script> var counts = JSON.parse("{{ test }}"); </script>

5 Comments

This doesn't work! and it looks like JSON.parse(test} has mismatching braces?
the parse is returning undefined on the variable, do I need some extra filters here?
There are mistake, should be <script> var counts = JSON.parse("{{ test }}"); </script> and it not sense because <script> var counts = {{ test }}; </script> will have same result and more short for this example. No reason make json twice.
@tbicr Yup, overlooked that one. You are right. Updated. Thanks.
You don't need JSON.parse() at all; use tojson for a HTML safe Javascript subset instead.
1

I've never liked having to use json.dumps. In this solution, arrays are not a special case. Just put your arrays and any other variable into an object:

Python

@app.route('/somePath')
def example():
    data = {
        'robotNames': ['Wall-E', 'Bender', 'Rosie']
    }
    return render_template('index.html', data=data)

JavaScript

<script>
    var flaskData = JSON.parse('{{data | tojson | safe}}');

    var robots = flaskData.robotNames;
    robots.forEach(function (robot) {
        console.log(robot);
    });
</script>

Comments

0

You try to return dictionary from your python showpage function like following and it will work:

def showpage():
    """Your logic for getting the list to return """
    test_dict = {"data_list": [1,2,3,4,5]}
    return render_template("sample.html", test=test_dict)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.