简体   繁体   English

django静态标签中的Javascript变量

[英]Javascript variables in django static tag

My situation: 我的情况:
In a Django template I would like to use something like this (currently wrong): 在Django模板中,我想使用类似这样的东西(当前是错误的):

<script>
   var myimg1='img1.jpg';
   var myimg2='img2.jpg';
</script>

and somewhere else, being context_var a proper context variable: 在其他地方,context_var是适当的上下文变量:

<img src="{% if context_var %}
            {% static myimg1 %}
          {% else %}
            {% static myimg2 %}  
          {% endif %}" />

How can I get the same result in a simple way? 如何以简单的方式获得相同的结果?
There is no simple way to define a template variable within the template, right? 没有简单的方法可以在模板中定义模板变量,对吗?

Well, you can define a template variable like this: 好了,您可以定义一个模板变量,如下所示:

{% with myimg1="img1.jpg" myimg2="img2.jpg" %}

<script>
   var myimg1={{ myimg1 }};
   var myimg2={{ myimg2 }};
</script>

<img src="{% if context_var %}
            {% static myimg1 %}
          {% else %}
            {% static myimg2 %}  
          {% endif %}" />

{% endwith %}

But Django template philosophy frowns upon such things. 但是Django模板哲学对此并不满意。 To quote: 报价:

The template system intentionally doesn't allow the following: 模板系统故意不允许以下操作:

  • Assignment to variables 分配变量
  • Advanced logic 先进的逻辑

It is best to pass them as context variables from your view. 最好将它们作为上下文变量从您的视图传递。

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

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