flask - WTForms 在 Jinja2 中使用引号

标签 flask jinja2

我有以下 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(&quot;name&quot;);">...</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="&#34;show=true&#34;">

代替

<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/

相关文章:

javascript - TemplateSyntaxError 无法解析其余部分

python - 在 Python 中访问未知的查询参数

ansible - 如果列表中的任何项目为 True (Ansible),则仅运行一次命令

python - 将表单数组发送到 Flask

python - 解析 mongoDB 引用的模式

python - 如何让这个 Flask 应用程序更加 DRY(连接到许多 oauth API)?

python - Flask-sqlalchemy 浏览器输出的列别名

flask - 检查 Flask html 页面中的变量条件

python - 缺少必需的位置参数(日期时间)

python - 使用(仅)SQLAlchemy Core 的 Flask 应用程序模式