admin管理员组

文章数量:1279083

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>

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>
Share Improve this question asked Mar 6, 2014 at 7:05 Nishant NawarkhedeNishant Nawarkhede 8,39813 gold badges61 silver badges83 bronze badges 6
  • 4 Not like that. Python and JavaScript execute at two totally different times. What are you trying to do and why? You could use AJAX, but it might be overkill – Ian Commented Mar 6, 2014 at 7:09
  • @lan , Actually i am trying to truncate some text using django template tag , And this processing is based on some javascript variable. – Nishant Nawarkhede Commented Mar 6, 2014 at 7:11
  • 1 @Nishant Django & JavaScript share different execution environment Server and Client respectively ... what you are trying to do is not correct. I will suggest if javascriptvar is so obvious use it on templates itselft – Anil Namde Commented Mar 6, 2014 at 7:13
  • How is the JS variable being set and why are you trying to base your Django logic on it? – Ian Commented Mar 6, 2014 at 7:14
  • Depends what u want to achieve. If just need to truncate text on client side u dont need django tag at all. If u need to truncate and save truncated text on server then use ajax – simar Commented Mar 6, 2014 at 7:17
 |  Show 1 more ment

1 Answer 1

Reset to default 11

No, the Django template is piled 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-pute 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> 

本文标签: pythonAccess Javascript variable in Django TemplateStack Overflow