简体   繁体   中英

Django: using context variable in a script

I have a class view that inherits from TemplateView 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 ( TemplateSyntaxError ):

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).

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.

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

</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM