Reputation: 329
I have a dynamically generated RadioField in a form that I render in a template
class F(Form):
pass
F.selection = RadioField(
'selection',
choices=options,
validators=[
DataRequired()
]
)
'options' is a an array of tuples that is generated, this works fine. It prints the options when I have this in my template
{% for subfield in form.selection %}
<p>
<tr>
<td>{{ subfield }}</td>
<td>{{ subfield.label }}</td>
</tr>
</p>
{% endfor %}
Issue that I am facing right now is that this gives me a set of radio buttons with a text next to it. In this case the 'title' of what I want people to chose between.
But I want to have additional info there, eg. a description, size, image maybe, etc.
I have currently tried making a list of tuples with this extra info and passing it to the template. I can access the extra info there but I can't figure out how to iterate over both sets of data at the same time
{% for item in data %}
<p>
{{ item[0] }}
{{ item[1] }}
{{ item[2] }}
</p>
{% endfor %}
what I want is to put this in one for loop so I can make pretty 'enhanced' options. Now I would use zip, but I can't do that in Jinja2 ( I think) and I can't zip it beforehand because the radiofield choices argument won't take that.
so any suggestions ?
Upvotes: 0
Views: 1318
Reputation: 2769
This will work, on back-end/Python side use:
form = TestRadio()
form.radio.choices = [('one', '1'), ('two', '2')]
extra_stuff = [('a', 'b', 'c'), ('d', 'e', 'f')]
TestRadio
inherits from a flask-wtf Form
, as below:
class TestRadio(Form):
radio = RadioField()
Assuming extra_stuff
has the same length as number of choices, then in jinja2:
<form>
<table>
{% for subfield in form.radio %}
<tr>
<td> {{ form.csrf_token }} </td>
<td> {{ subfield }} </td>
{% for item in extra_stuff[loop.index0] %}
<td> {{ item }} </td>
{% endfor %}
</tr>
{% endfor %}
</table>
</form>
In summary set choices on the Python side, within a view function. The trick is this loop
variable I used. It tracks the index of the outer level for loop. (http://jinja.pocoo.org/docs/dev/tricks/#accessing-the-parent-loop)
Regarding adding images:
http://flask.pocoo.org/docs/0.10/quickstart/#static-files
Upvotes: 2