将 css 类添加到 wtform 中的字段 [英] Add a css class to a field in wtform

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

问题描述

我正在使用 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 是从表单导入的,f 是基础表单的一个实例):

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

产生这个输出(没有类):

produces this output (no class):

<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:

金贾:

    {{ 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.

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

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