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

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

问题描述

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

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.

示例代码:

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

它不起作用.请问有什么建议吗?

It doesn't work. Any suggestions please?

推荐答案

除了将变量封装在一个字符串中之外,另一种替代方案是 jquery 以获取利润:

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

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

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}}">

然后在javascript中做

then in the javascript do

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

这在以下方面具有优势:

this has advantage in:

  • javascript 不再绑定到 .html 页面
  • jquery 隐式强制数据

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

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