How to pass a Javascript variable in django template-tag

Hello i have this question

if have a variable

 var a = True

can i use the variable like

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

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

2 answers

  • answered 2018-07-12 07:45 Adelin

    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)

  • answered 2018-07-12 07:55 Rakesh

    You can do the html modification in JavaScript


        var a = true;
        if (a){ 
           document.getElementById("your_h2_tag_ID").innerHTML = "True";
           document.getElementById("your_h2_tag_ID").innerHTML = "False";