Django: using context variable in a script
<p>I have a class view that inherits from <code>TemplateView</code> and sets a context variable to a serialized list of items:</p>

<pre><code>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
</code></pre>

<p>As is noted in <a href="http://stackoverflow.com/questions/298772/django-template-variables-and-javascript">this post</a> you're supposed to be able to access Django variables from our Django templates in the following manner:</p>

<pre><code>&lt;script&gt;var items = {{ items }};&lt;/script&gt;
</code></pre>

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

<pre><code>Uncaught SyntaxError: Unexpected token &amp;
</code></pre>

<p>I also tried using the filter:</p>

<pre><code>&lt;script&gt;var items = {{ items | escapejs }};&lt;/script&gt;
</code></pre>

<p>Only to find another error, this time a Django one (<code>TemplateSyntaxError</code>):</p>

<pre><code>Could not parse the remainder: ' |  escapejs' from 'items | escapejs'
</code></pre>

<p>How can I solve this issue?</p>

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

<pre><code>&lt;script&gt;
  var items = "{{items}}";

&lt;/script&gt;
</code></pre>

javascript python django