Skip to content

Instantly share code, notes, and snippets.

@pwalsh
Forked from alienhaxor/_formhelpers.py
Last active September 5, 2022 17:44
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save pwalsh/d3eb06ad098abcc9cb1d to your computer and use it in GitHub Desktop.
Save pwalsh/d3eb06ad098abcc9cb1d to your computer and use it in GitHub Desktop.
A macro for rending WTForm fields in Jinja2 templates with Bootstrap 3 styling.
{% macro render_field(field) -%}
{% set with_label = kwargs.pop('with_label', False) %}
{% set placeholder = kwargs.pop('placeholder', field.label.text) %}
{% set class_ = kwargs.pop('class_', '') %}
{% if field.flags.required %}
{% set class_ = class_ + ' required' %}
{% endif %}
<div class="form-group {% if field.errors %}error{% endif %}">
{% if with_label %}
<label for="{{ field.id }}"
class="control-label{% if field.flags.required %} required{% endif %}">
{{ field.label.text }}
</label>
{% endif %}
{% if field.type == 'BooleanField' %}
<div class="checkbox">
<label>
{{ field(class_=class_, **kwargs) }}
{{ field.label.text|safe }}
</label>
</div>
{% else %}
{% if field.type in ('TextField', 'TextAreaField', 'PasswordField',
'IntegerField') %}
{% set class_ = class_ + ' input-xlarge form-control' %}
{% elif field.type == 'FileField' %}
{% set class_ = class_ + ' input-file form-control' %}
{% endif %}
{% if field.type == 'SelectField' %}
{{ field(class_=class_, **kwargs) }}
{% else %}
{{ field(class_=class_, placeholder=placeholder, **kwargs) }}
{% endif %}
{% endif %}
{% if field.errors %}
<span class="error help-inline">{{ field.errors|join(', ') }}</span>
{% endif %}
{% if field.description %}
<p class="help-block">{{ field.description|safe }}</p>
{% endif %}
</div>
{%- endmacro %}
@michaelgobz
Copy link

Can u please explain mo about that
N wat is the logic behind it

@dmkitui
Copy link

dmkitui commented Sep 17, 2020

Use of kwargs.pop removes the items from the field object even after refreshing the page. I had to use kwargs.get

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment