Skip to content

Instantly share code, notes, and snippets.

@ziboumima
Created June 18, 2014 21:52
Show Gist options
  • Select an option

  • Save ziboumima/fd18f81a212744a897fd to your computer and use it in GitHub Desktop.

Select an option

Save ziboumima/fd18f81a212744a897fd to your computer and use it in GitHub Desktop.
Jinja2 template for bootstrap form
{% macro form_field(field) -%}
{% set with_label = kwargs.pop('with_label', False) %}
{% set placeholder = '' %}
{% if not with_label %}
{% set placeholder = field.label.text %}
{% endif %}
{% if field.type=='BooleanField' %}
<div class="checkbox">
<label>
<input type="checkbox"> {{ field.label.text }}
</label>
</div>
{% else %}
<div class="form-group {% if field.errors %}error{% endif %}">
{% if with_label and not field.type=='BooleanField' and not field.type=='CSRFTokenField' %}
<label for="{{ field.id }}">
{{ field.label.text }}{% if field.flags.required %} *{% endif %}:
</label>
{% endif %}
{% set class_ = kwargs.pop('class_', '') %}
{% if field.type == 'BooleanField' %}
<div class="checkbox">
<label>
{{ field(class_=class_, **kwargs) }}
</label>
</div>
{% else %}
{% if field.type in ('TextField', 'TextAreaField', 'PasswordField') %}
{% elif field.type == 'FileField' %}
{% set class_ = class_ + ' input-file' %}
{% endif %}
{{ field(class_=class_, placeholder=placeholder, **kwargs) }}
{% 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>
{% endif %}
{%- endmacro %}
{% macro generate_form(form, method='post', action='', submit_text='Gửi') -%}
<form method="{{ method }}" action="{{ action }}" role="form">
<dl>
{% for f in form %}
{{ form_field(f, with_label=True, class_='form-control') }}
{% endfor %}
</dl>
<p><input type=submit class="btn btn-primary" value='Gửi'>
</form>
{%- endmacro %}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment