3

I have a front-end that generates bootstrap forms via a simple macro:

{% macro render_field(field, class_='', label_visible=true) -%}

<div class="form-group {% if field.errors %} has-error {% endif %}">
    {% if (field.type != 'HiddenField' and field.type !='CSRFTokenField') and label_visible %}
        <label for="{{ field.id }}" class="control-label">{{ field.label }}</label>
    {% endif %}
    {{ field(class_='form-control', **kwargs) }}
    {% if field.errors %}
        {% for e in field.errors %}
            <p class="help-block">{{ e }}</p>
        {% endfor %}
    {% endif %}
</div>

{%- endmacro %}

A wtform that I use looks like this:

class CommentForm(Form):
    comment = TextAreaField(validators=[DataRequired('Please enter your comment.')])

Is it possible to add front-end validation in the form of aria-required="true" for the fields that have as validator DataRequired?

If so, how?

Tim
  • 2,000
  • 4
  • 27
  • 45

2 Answers2

6

Create a Dictionary with the pair or pairs of properties to add to your field inside your macro in Jinja:

{% set attribs = {'aria-required':"true"}  %}
{{ field(class_="form-control", **attribs) }}

Also you could do it inline

{{ field(class="form-control", **{'aria-required':"true"} ) }}

either way is good

erikwco
  • 139
  • 1
  • 7
0

You need to pass the attribute to the field. Unfortunately, you can't do this directly because of the hyphen in the attribute name. While erikwco's suggestion will work, it prevents you from passing kwargs into the field if you are adding the attribute as part of a macro. It seems that Jinja only a single **dict to be expanded in a given function.

The solution is to modify the kwargs dictionary:

{% do kwargs.update({'aria-required': "true"}) %}
{{ field(class_="form-control", **kwargs) }}

For this to work, you will likely need to add the do extension to jinja during app initialization:

app.jinja_env.add_extension('jinja2.ext.do')
Nick K9
  • 3,885
  • 1
  • 29
  • 62