简体   繁体   English

如何在Django模板标签中传递Javascript变量

[英]How to pass a Javascript variable in django template-tag

Hello i have this question 你好我有这个问题

if have a variable 如果有一个变量

<script>
 var a = True
<script>

can i use the variable like 我可以像这样使用变量吗

{% if a %}
  <h1> True</h1>
{%else%}
  <h1> False </h1>
{%endif%}

The both pieces of code are in the same page 这两段代码在同一页面中

I don't want to use filters it will complicate a lot my work Thank you 我不想使用过滤器,这会使我的工作变得非常复杂。谢谢

You can do the html modification in JavaScript 您可以在JavaScript中进行html修改

Ex: 例如:

<script>
    var a = true;
    if (a){ 
       document.getElementById("your_h2_tag_ID").innerHTML = "True";
    }else{
       document.getElementById("your_h2_tag_ID").innerHTML = "False";
    }
<script>

No, you can't. 不,你不能。 For Django, var a = True is just a string. 对于Django, var a = True只是一个字符串。

Django is the one that creates the HTML and tells the browser what strings to use, and the browser will interpret the string and find it to be JavaScript, so it'll execute and finally see that a is a boolean. Django是创建HTML并告诉浏览器要使用哪些字符串的版本,浏览器将解释该字符串并将其查找为JavaScript,因此它将执行并最终看到a是布尔值。

By the time it does that, Django is long gone 到那时,Django已经不复存在了

The only way you can tell django to use a as a boolean, is to make another request to the server, sending a as a JSON or querystring parameter , and later interpret the request from python/django and use it in templates. 您可以告诉django将a用作布尔值的唯一方法是向服务器发出另一个请求, a作为JSON或querystring参数发送 ,然后从python / django解释该请求并将其在模板中使用。 (quite a costly task) (非常昂贵的任务)

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

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