JavaScript 使用 Jinja 模板中呈现的数据引发 SyntaxError [英] JavaScript raises SyntaxError with data rendered in Jinja template

查看:23
本文介绍了JavaScript 使用 Jinja 模板中呈现的数据引发 SyntaxError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将数据作为 JSON 从 Flask 路由传递到呈现 JavaScript 的 Jinja 模板.我想使用 JavaScript 遍历数据.浏览器显示 SyntaxError: Unexpected token '&'.需要一个属性名称. 当对呈现的数据调用 JSON.parse 时.如何在 JavaScript 中使用呈现的 JSON 数据?

I am trying to pass data as JSON from a Flask route to a Jinja template rendering JavaScript. I want to iterate over the data using JavaScript. The browser shows SyntaxError: Unexpected token '&'. Expected a property name. when JSON.parse is called on the rendered data. How do I use rendered JSON data in JavaScript?

var obj = JSON.parse({{ data }})
for (i in obj){
   document.write(obj[i].text + "<br />");
}

def get_nodes(node):
    d = {}
    if node == "Root":
        d["text"] = node
    else:
        d["text"] = node.name

    getchildren = get_children(node)
    if getchildren:
        d["nodes"] = [get_nodes(child) for child in getchildren]
    return d

tree = get_nodes("Root")
return render_template("folder.html", data=tree)

如果我只是把 {{ data }} 放在 HTML 部分,我看到的看起来是正确的.

If I just put {{ data }} in the HTML part, what I see looks correct.

{'text': 'Root', 'nodes': [{'text': u'Prosjekt3'}, {'text': u'Prosjekt4', 'nodes': [{'text': u'mappe8'}]}]}

推荐答案

Flask 的 Jinja 环境自动转义 HTML 模板中呈现的数据.这是为了避免在开发人员尝试呈现不受信任的用户输入时出现安全问题.

Flask's Jinja environment automatically escapes data rendered in HTML templates. This is to avoid security issues if the dev tries to render untrusted user input.

由于您传递的是要作为 JSON 处理的 Python 对象,因此 Flask 提供了 tojson 过滤器,该过滤器可自动将数据转储为 JSON 并将其标记为安全.

Since you are passing a Python object to be treated as JSON, Flask provides the tojson filter which automatically dumps the data to JSON and marks it safe.

return render_template('tree.html', tree=tree)

var tree = {{ tree|tojson }};

当您只查看以 HTML 格式呈现的数据时,它看起来是正确的,因为浏览器将转义符号显示为真正的符号(尽管在这种情况下,您看到的是 Python dict 的字符串表示形式,而不是 JSON,因此有还有一些问题,比如 u 标记).

When you just look at the data rendered in HTML, it looks correct because the browser displays the escaped symbols as the real symbols (although in this case you're seeing the string representation of a Python dict, not JSON, so there's still some issues like u markers).

以前版本的 Flask 没有将转储的数据标记为安全的,因此您可能会遇到诸如 {{ tree|tojson|safe }} 之类的示例,这不再需要.

Previous versions of Flask didn't mark the dumped data safe, so you might come across examples like {{ tree|tojson|safe }}, which isn't required anymore.

如果您没有渲染 JSON(或者您已经将 JSON 转储为字符串),您可以使用 safe 过滤器告诉 Jinja 数据可以安全渲染而无需转义.

If you're not rendering JSON (or you already dumped the JSON to a string), you can tell Jinja that data is safe to render without escaping by using the safe filter.

# already dumped to json, so tojson would double-encode it
return render_template('tree.html', tree=json.dumps(tree))

var tree = {{ tree|safe }};

您也可以在渲染之前将字符串包裹在 Markup 中,它相当于 safe 过滤器.

You can also wrap the string in Markup before rendering it, it's equivalent to the safe filter.

# already dumped and marked safe
return render_template('tree.html', tree=Markup(json.dumps(tree)))

var tree = {{ tree }};

<小时>

如果您不将此数据传递给 JavaScript,而是在 Jinja 中使用它,则不需要 JSON.传递实际的 Python 数据,不要对其调用 tojson,并像使用模板中的任何其他数据一样使用它.


If you're not passing this data to JavaScript, but using it in Jinja instead, you don't need JSON. Pass the actual Python data, don't call tojson on it, and use it as you would any other data in the template.

return render_template('tree.html', tree=tree)

{% for item in tree %}
    <li>{{ item }}</li>
{% endfor %}

这篇关于JavaScript 使用 Jinja 模板中呈现的数据引发 SyntaxError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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