简体   繁体   中英

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

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

By the time it does that, Django is long gone

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. (quite a costly task)

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