我通过Flask WTF生成一个表单。
相关复选框如下所示:
conditions = BooleanField(
"I agree to the above conditions.", validators=[DataRequired()])
我希望I agree
在句子的其余部分用粗体或strong-NOT。
我不能传入HTML标记,因为它们会被转义并呈现为文本。
这看起来像这样:
[] <strong>I agree</strong> to the above conditions.
我想得到这个结果:
我同意上述条件。
这可能吗?
谢谢你的提示。
感谢@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
过滤器。
这个答案受到以下讨论的启发:
使用Flask/Jinja2 将HTML传递到模板
这不是一个完美的解决方案,因为现在HTML和Python混合在表单定义中,但看起来你必须做出妥协。
一个简单的解决方案就是在模板中执行。代替:
{{ user_form.conditions.errors }}{{ user_form.conditions.label_tag }}<br />{{ user_form.conditions }}
do:
{{ 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对象在__init__
中都有一个render_kwarg。
render_kw(dict(–如果提供,则提供一个字典,该字典提供将在渲染时提供给小部件的默认关键字。
渲染模板时,Jinja2将读取此render_kw。在您的情况下,您可以定义:
conditions = BooleanField(
"I agree to the above conditions.", validators=[DataRequired()],
render_kw={"style": "font-weight: bold;")
模板时渲染
Jinja2渲染时,可以通过调用字段来指定其他渲染选项。
form.field()
__call__(**kwargs)
:将此字段渲染为HTML,使用关键字args作为附加属性。[…]
在所有的WTFormsHTML小部件中,关键字参数都被转换为HTML属性,尽管在理论上小部件可以自由地做任何事情wants提供的关键字参数,而小部件不必甚至做任何与HTML相关的事情。
所以在你的模板文件中,你可以做这样的事情:
{{ form.field(style="font-weight: bold;") }}
注意class关键字有一个异常,可能是由其他人保留的,那么关键字应该是class_
来源:字段-WTForms文档
我在烧瓶1.1.2上使用WTForm 2.3.3,由于将标签本身、label_tag等管道连接到safe
对我不起作用,所以我最终使用了以下内容:
{{ field.label.text|safe }}