javascript占位符的转义Jinja模板 [英] Escaping jinja template for javascript place holder
问题描述
我想将JavaScript变量${channels[i]}
传递给我的jinja2
模板,作为链接标签的href
属性的占位符.
I want to pass a javascript variable ${channels[i]}
to my jinja2
template as a placeholder for the href
attribute of the link tag.
我尝试了{% raw %}{% endraw %}
标记到转义"
html实体,但是jinja2
似乎抛出异常,因为%
是一个无法识别的字符.
I have tried {% raw %}{% endraw %}
tags to escape "
html entity but it seems that the jinja2
throws an exception as %
is an unidentified character.
在下面查看我的代码:
for(i=0; i<=channels.length-1; i++) {
console.log(channels[i])
const li = document.createElement("li");
li.innerHTML = `<a href="{{ url_for('channel', channel_name = ${channels[i]}) }}" >${channels[i]}</a>`;
ul.append(li);
}
任何帮助或其他任何完成任务的方法将不胜感激
any help or any other method to accomplish the task would be much appreciated
推荐答案
您正在混合东西,无法在jinja2
表达式{{ .. }}
中评估javascript变量.
you are mixing things, you can't evaluate javascript variables in jinja2
expression {{ .. }}
.
jinja2
在服务器端上呈现您的模板,并将HTML输出提供给客户端(浏览器),而javascipt(您的代码) )在客户端(浏览器)上操作接收到的HTML的DOM
.那么他们如何互相交谈呢?
您有3个选择:
jinja2
renders your template on the server-side and the HTML output is served to the client-side (the browser), whereas the javascipt (your code) manipulates the DOM
of the received HTML on the client-side (the browser). so how they would talk to each other ?
you have 3 options:
- 使用
ajax
执行http请求(而不是您的情况) - 查看代码并将逻辑移至
jinja2
(强烈建议) - 或尝试使用此技巧:
- using
ajax
to perform http requests (not your case) - reviewing the code and moving the logic to
jinja2
(strongly recommended) - or trying this hack:
[..]
let href = "{{ url_for('channel', channel_name='CHANNEL_NAME'} }}".replace("CHANNEL_NAME", ${channels[i])
li.innerHTML = "<a href=" + href + ">${channels[i]}</a>";
[..]
请记住,jinja2
将呈现您的模板并提供以下输出:
bear in mind that jinja2
will render your template and serve this output:
for(i=0; i<= channels.length-1; i++) {
console.log(channels[i])
const li = document.createElement("li");
let href = "http://localhost:5000/channel/CHANNEL_NAME".replace("CHANNEL_NAME", ${channels[i])
li.innerHTML = "<a href=" + href + ">${channels[i]}</a>";
ul.append(li);
};
,并且一旦被客户端接收,就可以执行javascript代码,然后使用值${channels[i]}
and once received by the client, the javascript code can be executed and then process the replacement of the CHANNEL_NAME
token with the value of ${channels[i]}
这篇关于javascript占位符的转义Jinja模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!