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>
-
4Not 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 overkillIan– Ian2014年03月06日 07:09:22 +00:00Commented 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– Nishant Nawarkhede2014年03月06日 07:11:46 +00:00Commented 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 itselftAnil Namde– Anil Namde2014年03月06日 07:13:27 +00:00Commented 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– Ian2014年03月06日 07:14:13 +00:00Commented 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 ajaxsimar– simar2014年03月06日 07:17:59 +00:00Commented Mar 6, 2014 at 7:17
1 Answer 1
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>