{# Render a form field's label with visual aid to see if it's required. #}
{%- macro field_label(f) -%}
  <label for="{{ f.id }}">
    {%- if f.flags.required -%}
      <strong>{{ f.label.text }}</strong>
    {%- else %}
      {{ f.label.text }}
    {%- endif %}
  </label>
{%- endmacro -%}


{# Render a form field's errors. #}
{%- macro field_errors(f) -%}
  {% if f.errors %}
    <ul class="list-unstyled text-danger field-error">
      {% for error in f.errors %}
        <li>{{ error | e }}</li>
      {% endfor %}
    </ul>
  {% endif %}
{%- endmacro -%}


{# Render a form field. #}
{%- macro field(f, css_class='form-control') -%}
  {{ f(class=css_class, **kwargs) }}
{%- endmacro -%}


{# Render a checkbox field. #}
{%- macro checkbox_field(f) -%}
  {{ f(type='checkbox', **kwargs) }} {{ f.label }}
{%- endmacro -%}


{# Render a form group with errors for various field types. #}
{%- macro form_group(f, css_class='') -%}
  {% if f.errors %}
    {% set css_class = css_class + ' has-error ' + kwargs.pop('class', '') %}
  {% endif %}

  {% if f.type == 'BooleanField' %}
    <div class="checkbox {{ css_class }}">
    {{ checkbox_field(f, **kwargs) }}
  {% else %}
    <div class="form-group {{ css_class }}">
    {{ field_label(f) }}
    {{ field(f, **kwargs) }}
  {% endif %}

    {{ field_errors(f) }}
    {{ caller () }}
  </div>
{%- endmacro %}


{# Render a form tag that contains a CSRF token and all hidden fields. #}
{%- macro form_tag(endpoint, fid='', css_class='', method='post') -%}
  <form action="{{ url_for(endpoint, **kwargs) }}" method="{{ method }}"
        id="{{ fid }}" class="{{ css_class }}" role="form">
    {{ form.hidden_tag() }}
    {{ caller () }}
  </form>
{%- endmacro -%}


{# Render a form for searching. #}
{%- macro search(endpoint) -%}
  {% call form_tag(endpoint, method='get') %}
    <label for="q"></label>
    <div class="input-group md-margin-bottom">
      <input type="text" class="form-control"
             id="q" name="q" value="{{ request.args.get('q', '') }}"
             placeholder="Search by typing, then press enter...">
    <span class="input-group-addon">
      <i class="fa fa-fw fa-search"></i>
    </span>
    </div>
  {% endcall %}
{%- endmacro -%}
