简体   繁体   English

Django:在脚本中使用上下文变量

[英]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: 我有一个继承自TemplateView的类视图,并将一个上下文变量设置为项目的序列化列表:

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: 正如指出这篇文章你应该能够从我们的Django模板访问以下方式Django的变量:

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

However I am getting a JavaScript error, which I assume is caused because of automatic escaping: 但是我收到一个JavaScript错误,我认为这是由于自动转义引起的:

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 ): 只找到另一个错误,这次是Django错误( TemplateSyntaxError ):

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

How can I solve this issue? 我该如何解决这个问题?

PS: I am using Django 1.4. PS:我正在使用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 }} . 因此应该是{{ items|escapejs }}

Although as Sebastian points out, you probably want {{ items|safe }} instead. 尽管正如塞巴斯蒂安(Sebastian)指出的那样,您可能想要{{ items|safe }}来代替。

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

</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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