Skip to content

Instantly share code, notes, and snippets.

@zgoda zgoda/form.html

Created Aug 1, 2019
Embed
What would you like to do?
Jinja2 macros to render simple WTForms form with Bulma
{% macro field_description(field) %}
{% if field.errors %}
{% for error in field.errors %}
<p class="help is-danger">{{ error }}</p>
{% endfor %}
{% else %}
{% if field.description %}
<p class="help is-italic">{{ field.description }}</p>
{% endif %}
{% endif %}
{% endmacro %}
{% macro render_field(field) %}
<div class="field is-horizontal">
<div class="field-label">
{% if field.widget.input_type not in ('checkbox', 'radio') %}
<label class="label">{{ field.label.text|safe }}{% if field.flags.required %} <span class="has-text-danger has-text-weight-bold">*</span>{% endif %}</label>
{% endif %}
</div>
<div class="field-body">
{% if field.widget.input_type in ('checkbox', 'radio') or field.type == 'SelectField' %}
<div class="field is-narrow">
<div class="control">
{% if field.type == 'SelectField' %}
<div class="select is-fullwidth">
{{ field(**kwargs) }}
</div>
{% else %}
<label class="{{ field.widget.input_type }}">
{{ field(**kwargs) }} {{ field.label.text|safe }}
</label>
{% endif %}
</div>
{{ field_description(field) }}
</div>
{% else %}
<div class="field">
<div class="control">
{% if field.type == 'TextAreaField' %}
{{ field(class_='textarea') }}
{% else %}
{{ field(class_='input', **kwargs) }}
{% endif %}
</div>
{{ field_description(field) }}
</div>
{% endif %}
</div>
</div>
{% endmacro %}
{% macro form_errors(form, hiddens=True) %}
{%- if form.errors %}
{%- for fieldname, errors in form.errors.items() %}
{%- if (is_hidden_field(form[fieldname]) and hiddens) or (not is_hidden_field(form[fieldname]) and hiddens != 'only') %}
{%- for error in errors %}
<div class="help is-danger">{{ error }}</div>
{%- endfor %}
{%- endif %}
{%- endfor %}
{%- endif %}
{%- endmacro %}
{% macro render_form_fields(form) %}
{{ form.hidden_tag() }}
{{ form_errors(form, hiddens='only') }}
{%- for field in form %}
{% if not is_hidden_field(field) -%}
{{ render_field(field) }}
{%- endif %}
{%- endfor %}
{%- endmacro %}
{% macro render_form_buttons(buttons) %}
<div class="field is-horizontal">
<div class="field-label"></div>
<div class="field-body">
<div class="field">
<div class="control">
{%- for button in buttons %}
{{ button.render() }}&nbsp;
{%- endfor %}
</div>
</div>
</div>
</div>
{%- endmacro %}
{% macro render_form(form, action, width=6, box=True) %}
<div class="container">
<div class="columns is-centered">
<div class="column is-{{ width }}">
<form method="post" action="{{ action }}" role="form" novalidate{% if box %} class="box"{% endif %}>
{{ render_form_fields(form) }}
{{ render_form_buttons(form.buttons) }}
</form>
</div>
</div>
</div>
{%- endmacro %}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.