我有以下 WTForms 类:
from flask_wtf import FlaskForm
from wtforms import SelectField
class MonitorLevel(FlaskForm):
monitor = SelectField('Monitor', choices=MONITOR_CHOICES)
可以使用以下 jinja2 代码呈现:
{{ form.monitor() }}
但是,我想在值更改时执行 JS 脚本,所以我添加了以下内容:
{{ form.monitor(**{'onchange': 'sendForm();'}) }}
这很好用,但现在我想传递一个变量(它是一个字符串)作为参数:
{{ form.monitor(**{'onchange': 'sendForm("{}");'.format(variable)}) }}
但是,这呈现为:
<select id="monitor" name="monitor" onchange="sendForm("name");">...</select>
所以,我尝试使用 safe
函数来逃避它,但这不起作用。我也尝试通过以下方式转义引号:\",但效果不佳。
有没有在字典的值中添加引号的想法?
提前致谢
最佳答案
来自 WTForms 文档 https://wtforms.readthedocs.io/en/2.3.x/widgets/#widget-building-utilities :
WTForms uses MarkupSafe to escape unsafe HTML characters before rendering. You can mark a string using
markupsafe.Markup
to indicate that it should not be escaped.
没有使用 markupsafe.Markup
我有同样的错误:
{{ input_field(**{'@click': '"show=true"'})|safe }}
给予
<input @click=""show=true"">
代替
<input @click="'show=true'">
在 Jinja2 模板中使用 markupsafe
模块:
{{ input_field(**{'@click': markupsafe.Markup("show=true")})|safe }}
做的工作:
<input @click="show=true">
注意:WTForm 将字符串括在双引号 "
中,因此您需要平时注意 "
字符串。
错误的方式
{{ input_field(**{'@click': markupsafe.Markup('console.log("show=true")')})|safe }}
会导致
<input @click="console.log("show=true")">
这是错误的(一个字符串不在另一个字符串中)。
好方法
{{ input_field(**{'@click': markupsafe.Markup("console.log('show=true')")})|safe }}
会给予
<input @click="console.log('show=true')"
关于flask - WTForms 在 Jinja2 中使用引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50455145/