向wtform中的字段添加一个css类 [英] Add a css class to a field in wtform

查看:447
本文介绍了向wtform中的字段添加一个css类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用wtforms(和烧瓶)生成一个动态表单。我想添加一些自定义css类到我生成的字段,但到目前为止我一直无法这样做。使用我在这里找到的答案,我试图使用自定义窗口小部件添加此功能。它的实现方式与对该问题的回答几乎完全相同:

I'm generating a dynamic form using wtforms (and flask). I'd like to add some custom css classes to the fields I'm generating, but so far I've been unable to do so. Using the answer I found here, I've attempted to use a custom widget to add this functionality. It is implemented in almost the exact same way as the answer on that question:

class ClassedWidgetMixin(object):
  """Adds the field's name as a class.

  (when subclassed with any WTForms Field type).
  """

  def __init__(self, *args, **kwargs):
    print 'got to classed widget'
    super(ClassedWidgetMixin, self).__init__(*args, **kwargs)

  def __call__(self, field, **kwargs):
    print 'got to call'
    c = kwargs.pop('class', '') or kwargs.pop('class_', '')
    # kwargs['class'] = u'%s %s' % (field.name, c)
    kwargs['class'] = u'%s %s' % ('testclass', c)
    return super(ClassedWidgetMixin, self).__call__(field, **kwargs)


class ClassedTextField(TextField, ClassedWidgetMixin):
  print 'got to classed text field'



在视图中,我这样做是为了创建字段(ClassedTextField从表单导入,是基本形式的实例):

In the View, I do this to create the field (ClassedTextField is imported from forms, and f is an instance of the base form):

  f.test_field = forms.ClassedTextField('Test Name')

表单的其余部分正确创建,但此jinja:

The rest of the form is created correctly, but this jinja:

{{f.test_field}}

输出(无类):

<input id="test_field" name="test_field" type="text" value="">

任何提示都会很棒,谢谢。

Any tips would be great, thanks.

推荐答案

你实际上不需要去小部件级别将HTML类属性附加到字段的呈现。您可以使用jinja模板中的 class _ 参数简单地指定它。

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.

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

将产生以下HTML ::

will result in the following HTML::

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

动态地执行此操作,例如,使用表单的名称作为HTML类属性的值,您可以执行以下操作:

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) }}

输出:

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

有关注入HTML属性的更多信息,请查看官方文档

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

这篇关于向wtform中的字段添加一个css类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆