如何将javascript值设置为jinja变量 [英] How to set javascript value to jinja variable

查看:158
本文介绍了如何将javascript值设置为jinja变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我们可以像这样将Jinja变量设置为js变量.

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

var x = {{ 'value' }}

但是我正试图做相反的事情.即我正在尝试将javascript值设置为jinja变量.我尝试了以下方法,但无济于事.

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是javascript变量.

x is javascript variable.

有什么方法可以实现这一目标.

is there any way to achieve this.

推荐答案

这是不可能的,它反映了您对Web应用程序体系结构的理解中的一个深层问题. jinja2是在服务器上运行的Python模板引擎.您正在谈论的JavaScript正在浏览器中运行.

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.

当服务器接收到请求时,它会处理jinja2模板以获取将发送给客户端的响应.您不能将Jinja变量设置为js变量",而是可以以最终为JavaScript变量分配一个Jinja2变量中的值的方式呈现页面. IE.您从jinja2模板中的var x = {{ value }}开始; jinja2在渲染期间将其转换为var x = 42;然后将渲染的结果发送到客户端,客户端将其作为JavaScript执行,并为x分配值42.这里有一个时间序列(Python-> jinja2->呈现的页面源代码-> JavaScript),这意味着您无法做自己想做的事情:jinja2变量和JavaScript变量不同时存在,也不是在同一位置,并且不可能为jinja2变量分配JavaScript值.

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.

为了将值42发送到Python(可能以后再发送到jinja2),您需要发出一个将值从客户端发送到服务器的请求:表单提交或AJAX请求.

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.

如果您确切描述您认为需要将javascript值设置为jinja变量",则可能会得到更好的响应.

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".

这篇关于如何将javascript值设置为jinja变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆