在Django模板中访问Javascript变量 [英] Access Javascript variable in Django Template
问题描述
有没有办法在 Django
模板标签中访问
javascript
code>?
我可以做这样的事情,
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>
推荐答案
不,Django模板是编译服务器端。然后将其发送到浏览器执行JavaScript的客户端。在客户端浏览器上执行的JavaScript没有任何改变可能会对模板产生影响。那时候太迟了
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.
然而,JavaScript可能会像服务器的另一个请求一样做更多的信息。或者您可以在将服务器发送给客户端之前预先计算服务器的值。如果你更清楚你正在努力做什么,我们应该能够帮助。
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.
当然可以使用Django模板来设置JavaScript变量。
You can of course use Django templates to set JavaScript variables.
<script>
var myVar = '{{ py_var }}';
</script>
这篇关于在Django模板中访问Javascript变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!