1

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

5
  • 1
    try using {{ items|safe }} Commented Sep 13, 2016 at 9:52
  • Instead of passing the json through the template to your script you could add an endpoint view which serializes the data you need and request this from javascript itself with something like $.getJSON("your_view_url", function(data) { } Commented Sep 13, 2016 at 9:55
  • @SebastianBurzyński I get the same error than with escapejs: Could not parse the remainder: ' | safe' from 'items | safe' Commented Sep 13, 2016 at 9:56
  • 1
    @JackEvans that's what I initially did, I ajax'ed the items as JSON in another request, but it seems redundant now, since I can do it all in just one request. Commented Sep 13, 2016 at 9:56
  • 1
    As Daniel said, you cannot use spaces in between your "|" sign. Commented Sep 13, 2016 at 9:58

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Oh wow that was it. Can you explain what were the whitespaces causing? And why should safe be used instead of escapejs?
The template parser is pretty basic, it just isn't clever enough to deal with spaces there. escapejs adds additional escaping for characters that have meaning in JS; you want the opposite, ie to pass the JSON exactly as is without escaping.
1
<script>
  var items = "{{items}}";

</script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.