Skip to content

Instantly share code, notes, and snippets.

@alienhaxor
Forked from maximebf/gist:3986659
Last active September 5, 2022 17:42
Show Gist options
  • Save alienhaxor/6876797 to your computer and use it in GitHub Desktop.
Save alienhaxor/6876797 to your computer and use it in GitHub Desktop.
Jinja2 macro to render WTForms fields with Twitter Bootstrap. This fork renders the fields according to bootstrap 3.0.0
{% macro render_field(field) -%}
{% set with_label = kwargs.pop('with_label', False) %}
{% set placeholder = '' %}
{% if not with_label %}
{% set placeholder = field.label.text %}
{% endif %}
<div class="form-group {% if field.errors %}error{% endif %}">
{% if with_label %}
<label for="{{ field.id }}" class="control-label">
{{ field.label.text }}{% if field.flags.required %} *{% endif %}:
</label>
{% endif %}
{% set class_ = kwargs.pop('class_', '') %}
{% if field.flags.required %}
{% set class_ = class_ + ' required' %}
{% 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') %}
{% 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 %}
@floer32
Copy link

floer32 commented Jul 23, 2014

thank you!!!

@AndreMiras
Copy link

Great, I would add 'URLField' to ('TextField', 'TextAreaField', 'PasswordField') tuple.

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