无法将jinja2变量传递给JavaScript片段 [英] Unable to pass jinja2 variables into javascript snippet

查看:171
本文介绍了无法将jinja2变量传递给JavaScript片段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将jinja2数据传递给javascript。
我有一个Flask REST的网址为 / logs /< test_case_name>
我正在尝试使用 .getJSON()来查询上面的URL,因此会想要将具有testcasename的jinja2数据传递给 .getJSON 函数。



示例代码:

 < script type =text / javascript> 
alert({{name}});
< / script>

不起作用。
有什么建议吗?除了将变量封装在一个字符串中,另一个替代方案是jquery的获利: / p>

将模板语言与javascript混合通常是一个坏主意。另一种方法是使用html作为代理 - 将名称存储在元素中,如

 < meta id =my -datadata-name ={{name}}data-other ={{other}}> 

然后在javascript中执行

<$ p $ (); $(code)var djangoData = $('#my-data')。

这样做有以下优点:


  • javascript不再绑定到.html页面

  • jquery强制隐藏数据


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 .getJSON function.

sample code:

<script type="text/javascript">
  alert({{name}});
</script>

It doesn't work. Any suggestions please?

解决方案

other than encapsulating the variable in a string, an alternate is jquery for profit:

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

<meta id="my-data" data-name="{{name}}" data-other="{{other}}">

then in the javascript do

var djangoData = $('#my-data').data();

this has advantage in:

  • javascript no longer tied to the .html page
  • jquery coerces data implicitly

这篇关于无法将jinja2变量传递给JavaScript片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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