Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
952 views
in Technique[技术] by (71.8m points)

flask - Add a css class to a field in wtform

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'

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...