简体   繁体   English

如何使用 Javascript 变量设置 jinja2 表达式?

[英]How to set a jinja2 expression with a Javascript variable?

How can I use a Jinja2 expression within a js function?如何在 js 函数中使用 Jinja2 表达式? I'd tried something similar to the lines below and the expression isn't working.我尝试了类似于下面几行的内容,但表达式不起作用。 The attribute fileList used in response is a list coming from flask through Json.响应中使用的属性 fileList 是来自flask 通过Json 的列表。

var response = JSON.parse(req.responseText);  
{% set myFiles = response.fileList %}

Jinja2 is a templating language. Jinja2 是一种模板语言。 Meaning all template expressions will be evaluated and replaced by either text or HTML code before even served to the client.这意味着所有模板表达式在提供给客户端之前都将被评估并替换为文本或 HTML 代码。 Whereas Javascript is a scripting language used on the client side.而 Javascript 是一种在客户端使用的脚本语言。

So there is actually no way to pass any values to a Jinja2 expression from Javascript as there simply don't exist any Jinja2 expressions on the client side because they have all been replaced already by text or html code.所以实际上没有办法将任何值从 Javascript 传递给 Jinja2 表达式,因为客户端根本不存在任何 Jinja2 表达式,因为它们都已经被文本或 html 代码替换了。

However if you simply want to pass any data from client to server there are a lot of ways to do that.但是,如果您只是想将任何数据从客户端传递到服务器,那么有很多方法可以做到这一点。 Probably the most fitting for you would be an Ajax call.可能最适合您的是Ajax调用。

I think you looking for including expression or statement in js.我认为您正在寻找在 js 中包含表达式或语句。 It's possible, use double quotes(" ").有可能,使用双引号(" ")。 One thing you can't directly add in the js file.你不能直接在js文件中添加一件事。 use your code at the end of the code在代码末尾使用您的代码

var response = JSON.parse(req.responseText);  
"{% set myFiles = response.fileList %}"

For Clear Understanding,为了清楚地理解,

app.py
@app.route('/')
def home():
    return render_template('index.html',check=0,text='hai')

index.html
<div>
.
.
.
</div>
<script>
var text = {{ text }} //Throws error
var text = "{{ text }}" //console it

{% if(check == 0) %}
    console.log('its true')
{% endif %}  //Throw error

"{% if(check == 0) %}"
    console.log('its true')
"{% endif %}"//Success
</script>

It's working for me.它对我有用。 vote if works投票如果有效

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM