使用Jinja2对JavaScript进行转义? [英] Escape strings for JavaScript using Jinja2?

查看:90
本文介绍了使用Jinja2对JavaScript进行转义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用Jinja2转义HTML,以便可以将其用作JavaScript(jQuery)中的字符串?

How do I escape HTML with Jinja2 so that it can be used as a string in JavaScript (jQuery)?

如果我使用的是Django的模板系统,我可以写:

If I were using Django's templating system I could write:

$("#mydiv").append("{{ html_string|escapejs }}");

Django的 |escapejs过滤器会转义html_string中的内容(例如,引号,特殊字符)可能会破坏此代码块的预期用途,但Jinja2似乎没有等效的过滤器(我在这里错了吗?).

Django's |escapejs filter would escape things in html_string (eg quotes, special chars) that could break the intended use of this code block, but Jinja2 does not seem to have an equivalent filter (am I wrong here?).

是否有比从Django复制/粘贴代码更干净的解决方案?

Is there a cleaner solution than copying/pasting the code from Django?

推荐答案

去年我遇到了类似的问题.不知道您是否正在使用,但是我的解决方案看起来像这样.

I faced a similar problem last year. Not sure whether you're using bottle, but my solution looked something like this.

import json

def escapejs(val):
    return json.dumps(str(val)) # *but see [Important Note] below to be safe

@app.route('/foo')
def foo():
    return bottle.jinja2_template('foo', template_settings={'filters': {'escapejs': escapejs}})

(由于在所有地方都使用过template_settings字典,所以我将它包装在辅助函数中,但在此示例中我将其保持简单.)

(I wrapped the template_settings dict in a helper function since I used it everywhere, but I kept it simple in this example.)

不幸的是,它不像内置的jinja2过滤器那么简单,但是我能够愉快地使用它-特别是考虑到我还添加了其他几个自定义过滤器.

Unfortunately, it's not as simple as a builtin jinja2 filter, but I was able to live with it happily--especially considering that I had several other custom filters to add, too.

重要说明:@medmunds的以下技巧提示了他的精妙注释,提醒我们json.dumps不是XSS安全的. IOW,您不希望在面向互联网的生产服务器中使用它.建议编写一个更安全的JSON转义例程 (或者窃取django的–对不起,我知道您希望避免这种情况)并调用它而不是使用json.dumps.

Important Note: Hat tip to @medmunds's for his astute comment below, reminding us that json.dumps is not XSS-safe. IOW, you wouldn't want to use it in a production, internet-facing server. Recommendation is to write a safer json escape routine (or steal django's--sorry OP, I know you were hoping to avoid that) and call that instead of using json.dumps.

这篇关于使用Jinja2对JavaScript进行转义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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