dabadaba dabadaba - 11 months ago 36
Python Question

Django: using context variable in a script

I have a class view that inherits from

and sets a context variable to a serialized list of items:

class MyView(TemplateView):
def get_context_data(self, **kwargs):
context = super(MyView, self).get_context_data(**kwargs)
context['items'] = serializers.serialize("json", items) # assume items is an existing list
return context

As is noted in this post you're supposed to be able to access Django variables from our Django templates in the following manner:

<script>var items = {{ items }};</script>

However I am getting a JavaScript error, which I assume is caused because of automatic escaping:

Uncaught SyntaxError: Unexpected token &

I also tried using the filter:

<script>var items = {{ items | escapejs }};</script>

Only to find another error, this time a Django one (

Could not parse the remainder: ' | escapejs' from 'items | escapejs'

How can I solve this issue?

PS: I am using Django 1.4. (and no, I cannot upgrade it to the most recent version).

Answer Source

You can't use spaces between a template variable, the filter character, and the filter itself. So it should be {{ items|escapejs }}.

Although as Sebastian points out, you probably want {{ items|safe }} instead.