Marek Jedliński
Marek Jedliński

Reputation: 7316

Select a radio button in a jinja2 template

I have a jinja2 template with a simple user preferences form. The preferences are passed as a python dictionary into the render_template() function. Depending on a setting, I need to mark one of the radio buttons in a group as checked.

Q: How to do it cleanly, without much code repetition?

Below is my current solution. It works, but it's ugly, and with more than 2 radio buttons, it would soon become hard to manage. There is probably a better way.

I use two string variables (for the 2 radio btns). One of them will be empty, and the other will be set to 'checked', according to the preference setting:

{% if user_prefs['when_done'] == 'index' %}
    {% set indexchecked = 'checked' %}
    {% set backchecked = '' %}
{% else %}
    {% set indexchecked = '' %}
    {% set backchecked = 'checked' %}
{% endif %}
<!-- With more radio buttons here, this would be a mess! -->

And then I use these strings in the template:

<form action="{{ url_for('prefs') }}" method="post">
    <fieldset>
        <div class="radio text-left">
        <p><strong>After completing a task:</strong></p>
          <label>
            <input type="radio" name="when_done" value="index" {{ indexchecked }}>
            Return to homepage
          </label>
          <br/>
          <label>
            <input type="radio" name="when_done" value="task" {{ taskchecked }}>
            Go to next task
          </label>
        </div>

        <div class="form-group">
            <button class="btn btn-default" type="submit">Update preferences</button>
        </div>
    </fieldset>
</form>

Upvotes: 3

Views: 6026

Answers (1)

LietKynes
LietKynes

Reputation: 3072

I would move the computation of indexchecked and backchecked from the template to the code. You can also use dictionary unpacking in order to pass less parameters to the render_template method.

do_index = user_prefs['when_done'] == 'index'
index_checked = 'checked' if do_index else ''
back_checked = '' if do_index else 'checked'

render_template('pages/something.html', form=some_form, index_checked=index_checked, back_checked=back_checked)

In order to reduce the number of passed parameters you can use a dict with unpacking:

template_parameters = dict(form=some_form, index_checked=index_checked, back_checked=back_checked)
render_template('pages/something.html', **template_parameters)

Upvotes: 1

Related Questions