Search code examples
javascriptdjangodictionaryapostrophe

How to deal with apostrophe when passing dicts from view to template?


I am trying to pass some dictionaries from a view to a javascript in my template.

The data in view.py looks like:

node_result = [{'y': 0.40750126710593004, 'x': 1}, {'y': 1.0, 'x': 0}, {'y': 0.10288900152052712, 'x': 0}]
edge_result = [{'source': {'y': 0.40750126710593004, 'x': 1}, 'target': {'y': 0.40750126710593004, 'x': 1}}]

In my template , I retrieve it this way:

var nodes = {{node_result}};

var links = {{edge_result}};

BUT, When I inspected the javascript using my browser I got this error:

enter image description here

Clearly, there is a problem with the apostrophes, so how can I transfer dictionary?

Note: This works when I copy+paste dictionaries directly in javascript


Solution

  • You need to first convert the dictionaries to JSON:

    json.dumps(node_result))
    

    and then in your template you should turn off the auto escape:

    {% autoescape off %}
    var nodes = {{node_result}};
    var links = {{edge_result}};
    {% endautoescape %}
    

    You can also do :

    var nodes = {{ node_result|safe }};
    var links = {{ edge_result|safe }};
    

    Documentation https://docs.djangoproject.com/en/1.8/ref/templates/builtins/