Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rendering html title attributes with Flask-WTForms field description

I am using the render_field macro presented on the Flask-WFT documentation page to render fields in long forms across different templates.

A field is defined like this

year_built = IntegerField(label='Year Built', 
             description='Year built, not the year of a major renovation.',
             validators=[validators.NumberRange(
                                    min=1700,  
                                    max=2012, 
                                    message="Between %(min)s and %(max)s")])

The macro looks like this...

{% macro render_field(field) %}
  <dt>{{ field.label }}
  <dd>{{ field(**kwargs)|safe }}
  {% if field.errors %}
    <ul class=errors>
    {% for error in field.errors %}
      <li>{{ error }}</li>
    {% endfor %}
    </ul>
  {% endif %}
  </dd>
{% endmacro %}

In the forms themselves the individual fields are placed using...

{{ render_field(form.year_built, class="input text")}}

What I cannot figure out is a way to use the description in the field object within the part of the macro that creates the HTML field field(**kwargs). I know that I can pass keywords to the render_field function but I am dealing with forms with more than 100 fields and setting the description in the forms.py and then setting it again as a title keyword in the template.html seems like unnecessary repletion. I would really like to use the macro to display a description as a title if it's there or just display the field without a title if its not.

Is there a way to add new entries to kwargs before the field() function runs?

like image 622
dnfehren Avatar asked Aug 16 '12 21:08

dnfehren


1 Answers

So it was much easier than I thought...

{% macro render_field(field) %}
  <dt>{{ field.label }}
  <dd>{{ field(title=field.description, **kwargs)|safe }}
  {% if field.errors %}
    <ul class=errors>
    {% for error in field.errors %}
      <li>{{ error }}</li>
    {% endfor %}
    </ul>
  {% endif %}
  </dd>
{% endmacro %}
like image 56
dnfehren Avatar answered Sep 20 '22 13:09

dnfehren