#1 by somas
Hi. I have a form which looks like this:
Lottery | Low pay | High pay | Choice
1 | 28 | 28 | [ ]
2 | 24 | 36 | [ ]
3 | 20 | 40 | [x]
4 | 16 | 50 | [ ]
Basically each lottery is an option for a IntegerField, but I need to render not just a label, but a whole row. Assuming I have a list of the form
Lotteries [
[1, 28, 28],
[2, 24...
]
I would render this in the template like this:
<tbody>
{{ for choice in form.lotteries }}
<tr>
<td class="text-center">Lottery {{C.Lotteries.{{forloop.counter0}}.0}}</td>
<td class="text-center">{{ C.Lotteries.{{forloop.counter0}}.1 }}</td>
<td class="text-center">{{ C.Lotteries.{{forloop.counter0}}.2 }}</td>
<td class="text-center">{{ choice }}</td>
</tr>
{{ endfor }}
</tbody>
Of course this won't work as you can't use forloop.counter just like that. But then, I don't know how I should tackle this issue: I can't just use choice labels because otree will escape any HTML I try to put in them. What should be the correct approach?
#2 by Chris_oTree
The template language does not support doing that. I recommend generating the raw HTML in vars_for_template, where you can use regular Python constructs like zip(), array indexing, etc.
#3 by Chris_oTree
Also take a look at the 'persist-raw' in otree-snippets, which will preserve the state of the radio buttons if the page gets reloaded.
#4 by somas
So, I pass to the template a variable which, among other, contains this fstring:
f"""<td class="text-center">{{{{ form.lottery.{i} }}}}</td>"""
The renderer then complains it cannot resolve form.lottery.0
I suspect the vars_for_template are evaluated before form_fields, so this approach would not work
for the record, the HTML generated by my vars_for_template is identical to hardcoded HTML which works, so it's not an error on how to reference formfield choices or things like that
#5 by somas
Nevermind, I indeed had an issue in how I had defined the options. Still, this approach does not work for me because variables are printed as is:
Lottery | Low pay | High pay | Choice
1 | 28 | 28 | {{ form.lottery.0 }}
2 | 24 | 36 | {{ form.lottery.1 }}
3 | 20 | 40 | {{ form.lottery.2 }}
4 | 16 | 50 | {{ form.lottery.3 }}
etc
#6 by Chris_oTree
Don't generate any {{}} characters. Just generate the whole table in vars_for_template, with the raw HTML code for the radio buttons, e.g. <input type="radio" name=...>