How to set javascript value to jinja variable

人盡茶涼 提交于 2020-01-21 11:54:26

问题


I know we can set Jinja variable to js variable like this.

var x = {{ 'value' }}

but I am trying to do the reverse. i.e I am trying to set javascript value to jinja variable. I tried the following but nothing worked.

{{value}} = x
{% set value = x %}
{% set value %} x {% endset %}

x is javascript variable.

is there any way to achieve this.


回答1:


This is not possible, and reflects a deep problem in your understanding of the web application architecture. jinja2 is a templating engine for Python, running on your server. JavaScript you are talking about is running in your browser.

When a server receives a request, it processes a jinja2 template to obtain the response it will send to the client. You cannot "set Jinja variable to js variable", you can render the page in such a way that eventually a JavaScript variable would be assigned a value that was in a Jinja2 variable. I.e. you start with var x = {{ value }} in jinja2 template; jinja2 transforms it into var x = 42 during its rendering; then the rendered result gets sent to the client, which executes it as JavaScript, assigning a value 42 to x. The fact that there is a temporal sequence here (Python -> jinja2 -> rendered page source -> JavaScript) means you can't do what you want to do: The jinja2 variable and the JavaScript variable don't exist at the same time, nor in the same place, and assigning a JavaScript value to a jinja2 variable is impossible.

In order to send the value 42 to Python (and possibly later to jinja2), you would need to make a request that would send that value from client to server: a form submission, or an AJAX request.

You might get a better response if you would describe exactly what you want to do that you think requires you to "set javascript value to jinja variable".



来源:https://stackoverflow.com/questions/43383808/how-to-set-javascript-value-to-jinja-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!