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>