Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access Javascript variable in Django Template

Is there is any way to access javascript variable in Django template tags ?
Can i do something like this ,

<!DOCTYPE html>
<html>
    <body>
    <script>
        var javascriptvar=0;
    </script>
    {% if javascriptvar==0 %}
         do this
    {% else %}
         do this
    {% endif %}
    </body>
</html>
like image 325
Nishant Nawarkhede Avatar asked Dec 19 '22 17:12

Nishant Nawarkhede


1 Answers

No, the Django template is compiled server side. It is then sent to the client where their browser executes the JavaScript. Nothing that is changed by the JavaScript executing on the client browser can have an affect on the template. It's too late at that point.

However the JavaScript could do something like make another request from the server for more information. Or you could just pre-compute the value on the server before you send it to the client. If you are more explicit about what you are trying to do we should be able to help.

You can of course use Django templates to set JavaScript variables.

<script>
    var myVar = '{{ py_var }}';
</script> 
like image 61
aychedee Avatar answered Dec 22 '22 11:12

aychedee