Python 无法将 jinja2 变量传递到 javascript 片段中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21626048/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Unable to pass jinja2 variables into javascript snippet
提问by deeshank
How do i pass jinja2 data into javascript.
I have a Flask REST url as /logs/<test_case_name>I am trying use .getJSON()to query the above URL and hence would want to pass the jinja2 data which has the testcasename to .getJSONfunction.
我如何将 jinja2 数据传递给 javascript。我有一个 Flask REST url,因为/logs/<test_case_name>我正在尝试使用它.getJSON()来查询上述 URL,因此我想传递具有 testcasename 的 jinja2 数据来.getJSON运行。
sample code:
示例代码:
<script type="text/javascript">
alert({{name}});
</script>
It doesn't work. Any suggestions please?
它不起作用。请问有什么建议吗?
采纳答案by rich tier
other than encapsulating the variable in a string, an alternate is jquery for profit:
除了将变量封装在字符串中之外,另一种替代方法是 jquery 以获取利润:
its generally a bad idea to mix template language with javascript. An alternative would be to use html as a proxy - store the name in an element like so
将模板语言与 javascript 混合通常是一个坏主意。另一种方法是使用 html 作为代理 - 将名称存储在这样的元素中
<meta id="my-data" data-name="{{name}}" data-other="{{other}}">
then in the javascript do
然后在javascript中做
var djangoData = $('#my-data').data();
this has advantage in:
这在以下方面具有优势:
- javascript no longer tied to the .html page
- jquery coerces data implicitly
- javascript 不再绑定到 .html 页面
- jquery 隐式强制数据
回答by ndpu
Try with quotes:
尝试使用引号:
alert("{{name}}");
回答by Suraj
This is how I did it
这就是我做到的
My html Element
我的 html 元素
<!--Proxy Tag for playlist data-->
<meta id="my_playlist_data" data-playlist="{{ playlist }}">
My script element
我的脚本元素
// use Jquery to get data from proxy Html element
var playlist_data = $('#my_playlist_data').data("playlist");
See .data()documenttation for more
有关更多信息,请参阅.data()文档
回答by mr_info
I know this is a kinda old topic, but since it attracts a lot of views I suppose some people are still looking for an answer.
我知道这是一个有点老的话题,但由于它吸引了很多观点,我想有些人仍在寻找答案。
Here's the simplest way to do it:
这是最简单的方法:
var name = {{name|tojson}};
It will 'parse' whatever 'name' is and display it correctly: https://sopython.com/canon/93/render-string-in-jinja-to-javascript-variable/
它会“解析”任何“名称”并正确显示它:https: //sopython.com/canon/93/render-string-in-jinja-to-javascript-variable/

