zip() as in python for a template?

58 views
Skip to first unread message

Pei-Hsun

unread,
May 25, 2022, 4:55:07 PM5/25/22
to oTree help & discussion
Dear all,

I was wondering if there is something like zip() as in python for a template. I want to use loop for a table in a template, whose three columns contains parameters for the forms in the same row and two different sets of forms. Thus, it would be easier to zip sets of forms together to run a loop.  For example, a table would look like this:

Image 001.jpg

Is it possible to do so in a template?

Thanks,
Pei-Hsun

Chris Crabbe

unread,
May 25, 2022, 6:33:04 PM5/25/22
to Pei-Hsun, oTree help & discussion
Hi Pei-Hsun -

In this situation I would prepare a list of dicts in vars_for_template, and then loop through that list in the template.

So if I prepared a list of dicts like this:

@staticmethod
def vars_for_template(player:Player):
    rval = {}
    qlist = []
    for q in range(len(params)):
        qdict = {}
        qdict['parameter'] = 'a=='+str(q)
        qdict['question_1'] = 'Questions 1 when a=='+str(q)
        qdict['question_2'] = 'Question 1 when a=='+str(q)
        list.append(qdict)
    rval['question_list'] = qlist
    return rval

This means in the template I can loop through "question_list" like this:

<table>
{{ for q in question_list }}
    <tr><td>{{ q.parameter }}</td>
        <td>{{ q.question_1 }}</td>
        <td>{{ q.question_2 }}</td></tr>
{{ endfor }}
</table>

Basically if you have a dict in the template, you can loop through its entries and access the keys like above.

Good luck,
--Chris

--
You received this message because you are subscribed to the Google Groups "oTree help & discussion" group.
To unsubscribe from this group and stop receiving emails from it, send an email to otree+un...@googlegroups.com.
To view this discussion on the web, visit https://groups.google.com/d/msgid/otree/e1a4c855-c0f5-425d-84b6-aad03e1a29e5n%40googlegroups.com.

Pei-Hsun

unread,
May 25, 2022, 10:16:23 PM5/25/22
to oTree help & discussion
Hi Chris,

sorry I did not explain my question well, but question 1 and question 2 are not literally the string I want to type. They are forms at the player level. Is it possible to loop two sets of forms?

Thanks,
Pei-Hsun

ccr...@gmail.com 在 2022年5月25日 星期三下午6:33:04 [UTC-4] 的信中寫道:

Chris @ oTree

unread,
May 25, 2022, 10:46:16 PM5/25/22
to Pei-Hsun, oTree help & discussion
See complex_form_layout in otree-snippets. 

Sent from my phone

On May 26, 2022, at 10:16 AM, Pei-Hsun <barry...@gmail.com> wrote:


Reply all
Reply to author
Forward
0 new messages