5

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>
asked Mar 6, 2014 at 7:05
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 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. 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 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? 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 Commented Mar 6, 2014 at 7:17

1 Answer 1

11

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> 
answered Mar 6, 2014 at 7:24

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.