Add a css class to a field in wtform

冷暖自知 提交于 2019-11-27 17:23:42

You actually don't need to go to the widget level to attach an HTML class attribute to the rendering of the field. You can simply specify it using the class_ parameter in the jinja template.

e.g.

    {{ form.email(class_="form-control") }}

will result in the following HTML::

    <input class="form-control" id="email" name="email" type="text" value="">

to do this dynamically, say, using the name of the form as the value of the HTML class attribute, you can do the following:

Jinja:

    {{ form.email(class_="form-style-"+form.email.name) }}

Output:

    <input class="form-style-email" id="email" name="email" type="text" value="">

For more information about injecting HTML attributes, check out the official documentation.

If you would like to programatically include the css class (or indeed, any other attributes) to the form field, then you can use the render_kw argument.

eg:

r_field = RadioField(
    'Label', 
    choices=[(1,'Enabled'),(0,'Disabled')], 
    render_kw={'class':'myclass','style':'font-size:150%'}
)

will render as:

<ul class="myclass" id="r_field" style="font-size:150%">
    <li><input id="r_field-0" name="r_field" type="radio" value="1"> <label for="r_field-0">Enabled</label></li>
    <li><input id="r_field-1" name="r_field" type="radio" value="0"> <label for="r_field-1">Disabled</label></li>
</ul>
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!