2

I'm programming in oTree (which is a Django based environment for social experiments) and I have the following problem. I defined some lists in Python and I'd like to import them and use them in an HTML template. If I print them in HTML I manage to see them without any problem, however, once I need to use them in Javascript, the program fails to read them and the single quotes of the elements of the list are converted in '. The list is imported like this var filtered_elements = {{ array }};.

I think the problem is exactly here, as JS cannot work with them. Do you have any suggestion on how to do that? I considered using JSON, but since I'm quite new to programming, I cannot understand if it's just a waste of time or there is a simpler way out. Thanks for your answers!

RexE
  • 17,085
  • 16
  • 58
  • 81
DenisDiderot
  • 57
  • 1
  • 9

2 Answers2

6

It sounds like your data is already JSON, otherwise you would be getting single quotes and u prefixes. So the only issue is Django autoescaping; you can disable it with the safe filter:

var filtered_elements = {{ array|safe }};
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • Thanks, it really seems to work. I had the impression that it might already be working on JSON to store data between modules and templates but I wasn't super sure about it yet... – DenisDiderot Jan 16 '17 at 15:02
6

Your data should be JSON, instead of putting the Python list into the contact directly, put "array": json.dumps(array) in the context dictionary.

The JSON string doesn't need HTML escaping inside a tag, but it does need JS escaping! Otherwise some string may include something like </script><script>absolutely anything goes here... to run arbitrary JavaScript, if the JSON contains user data.

So use |escapejs:

var filtered_elements = {{ array|escapejs}};
RemcoGerlich
  • 30,470
  • 6
  • 61
  • 79
  • 1
    Agree. btw, on the python side, when you call render (or any similar method), remember to use `json.dumps()` (ujson or simplejson). json is oriented from javascript, which provides a js-happy data serialization. – liuyruc Jan 16 '17 at 14:38
  • I don't understand, is it preferable |safe or |escapejs, what's the difference? – DenisDiderot Jan 16 '17 at 17:34
  • 1
    Usually Django automatically applies HTML escaping, that's what you saw (`'` to `'` and so on). JavaScript isn't HTML, so you don't need that. `|safe` merely marks a string as already escaped, so no escaping is applied to it. `|escapejs` applies the kind of escaping you need for JS inside a ` – RemcoGerlich Jan 16 '17 at 18:31