【问题标题】:WTForms use quotes in Jinja2WTForms 在 Jinja2 中使用引号
【发布时间】:2018-05-21 19:05:58
【问题描述】:

我有以下 WTForms 类:

from flask_wtf import FlaskForm
from wtforms import SelectField

class MonitorLevel(FlaskForm):
    monitor = SelectField('Monitor', choices=MONITOR_CHOICES)

可以使用以下 jinja2-code 渲染:

{{ 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 函数来逃避它,但这不起作用。我也尝试通过:\" 来转义引号,但这也不起作用。

在字典的值中添加引号有什么想法吗?

提前致谢,

【问题讨论】:

  • 什么会给{{ form.monitor(**{'onchange': 'sendForm("");'}) }}

标签: flask jinja2


【解决方案1】:

这种行为是正常的,WTForms 使用escape(s, quote=True) 来呈现 HTML 属性值 (escape documentation)

您可以在Github directly 上查看函数def html_params(**kwargs): 以获取更多信息。

基本上您不必更改代码,因为:

  1. Javascript 仍然像魅力一样工作,您的浏览器会即时转换 HTML 实体(sendForm() 运行 onchange)。
  2. 如果您在没有escape(s, quote=True) 的情况下打印,onchange="sendForm("name");" 不是有效的 HTML 属性。

【讨论】:

    【解决方案2】:

    来自 WTForms 文档https://wtforms.readthedocs.io/en/2.3.x/widgets/#widget-building-utilities

    WTForms 使用MarkupSafe 在渲染前转义不安全的 HTML 字符。您可以使用markupsafe.Markup 标记字符串以指示它不应被转义。

    不使用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')"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-07
      • 2015-01-20
      • 1970-01-01
      • 2017-06-10
      • 1970-01-01
      相关资源
      最近更新 更多