转义 javascript 占位符的 jinja 模板 [英] Escaping jinja template for javascript place holder

查看:23
本文介绍了转义 javascript 占位符的 jinja 模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一个 javascript 变量 ${channels[i]} 作为 href 属性的占位符传递给我的 jinja2 模板链接标签.

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 %} tags 转义 " 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代码,然后将CHANNEL_NAME令牌替换为${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屋!

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