是否可以在 Flask-WTForms 中设置标签的一部分样式?

Is it possible to style a part of a label in Flask-WTForms?

我通过 Flask-WTF 生成了一个表单。

相关复选框如下所示:

    conditions = BooleanField(
        "I agree to the above conditions.", validators=[DataRequired()])

我想要 I agree 粗体或粗体 - 不是 句子的其余部分。

我无法传入 HTML 标签,因为它们会被转义并呈现为文本。

这看起来像这样:

[] <strong>I agree</strong> to the above conditions.

我想得到这个结果:

我同意以上条件。

这可能吗?

感谢任何提示。

一个简单的解决方案就是在模板中执行此操作。而不是:

{{ user_form.conditions.errors }}{{ user_form.conditions.label_tag }}<br />{{ user_form.conditions }}

做:

{{ user_form.conditions.errors }}<strong>I agree</strong> to the above conditions.<br />{{ user_form.conditions }}

我还没有测试过这个,但你可以这样做:

conditions = BooleanField(
    "<strong>I agree</strong> to the above conditions.", validators=[DataRequired()])

然后,在模板中:

{{ user_form.conditions.errors }}{{ user_form.conditions.label_tag|safe }}<br />{{ user_form.conditions }}

有两种解决方法:

  • 使用 render_kw.
  • 创建字段时
  • 在模板中呈现字段时(调用字段时[form.field()])。

用样式初始化字段:

WTForms 中的所有 Field objects__init__.

中都有一个 render_kw arg

render_kw (dict) – If provided, a dictionary which provides default keywords that will be given to the widget at render time.

渲染模板时,Jinja2 将读取此 render_kw。 在您的情况下,您可以定义:

conditions = BooleanField(
    "I agree to the above conditions.", validators=[DataRequired()],
    render_kw={"style": "font-weight: bold;")

在模板化时渲染

当 Jinja2 渲染时,您可以通过调用字段来指定其他渲染选项。

form.field()

__call__(**kwargs): Render this field as HTML, using keyword args as additional attributes.

[...]

In all of the WTForms HTML widgets, keyword arguments are turned to HTML attributes, though in theory a widget is free to do anything it wants with the supplied keyword arguments, and widgets don’t have to even do anything related to HTML.

所以在你的模板文件中,你可以做类似的事情:

{{ form.field(style="font-weight: bold;") }}

注意class关键字有一个例外,可能是别的东西保留的,那么key应该是class_.


Source: Fields - WTForms Documencation

感谢@gaefan 的其他回答,我阅读了更多有关 Jinja 模板和 safe 过滤器的信息,并提出了另一个可行的解决方案。

from flask import Markup

label_for_conditions = Markup('<span class="customClass">I agree</span> to the above conditions.')
conditions = BooleanField(label_for_conditions, validators=[DataRequired()])

此解决方案甚至不需要模板中的 safe 过滤器。

此答案的灵感来自于以下讨论:

Passing HTML to template using Flask/Jinja2

这不是一个完美的解决方案,因为现在 HTML 和 Python 混合在表单定义中,但看起来你必须做出妥协。

我在 Flask 1.1.2 上使用 WTForm 2.3.3,我最终使用了以下内容,因为管道标签本身、label_tag 等到 safe 无法正常工作我,但这确实:

{{ field.label.text|safe }}