0

我有一个条件变量player.condition_var,它可以具有整数值 1、2 或 3。

现在,我想根据变量的值在 Results.html 页面上显示 1.jpg、2.jpg 或 3.jpg。但我不让它工作。怎么做到呢?

到目前为止我已经尝试过:

  1. 只需在 HTML 标记中包含 oTree 变量:<img src="{{static "folder/{{ player.condition_var }}.jpg" }}"/>

    => 错误信息TemplateSyntaxError: Error while parsing the PRINT tag AssertionError: {% static %} tag takes 1 argument (line 7, in "static")

  2. 将 if/else 与 javascript 一起使用:

    {{ block app_scripts }}
    <script>
      if (player['condition_var'] == 1) {
        imageshown = "folder/1.jpg"
      }
      else if (player['condition_var'] == 2) {
        imageshown = "folder/2.jpg"
      }
      else {
         imageshown = "folder/3.jpg"
      }
    </script>
    {{ endblock }}
    
    <img src="{{ static "imageshown" }}"/>
    

    => 无法加载图像。该变量似乎没有被其中一条路径填充。因此,HTML 代码尝试简单地加载“imageshown”

4

2 回答 2

0

I'm not sure what version your oTree is. For oTree < 5, you should return condition_var in vars_for_template of pages.py. In the template, try something like below.

<script>
    image = document.getElementById('imageshown');
    if ({{condition_var|json}} == 1) {
        image.src= "{% static '1.jpg' %}";
    }
    else if ({{condition_var|json == 2) {
        image.src= "{% static '2.jpg' %}";
    }
    else {
        image.src= "{% static '3.jpg' %}";
    }
</script>
<img id="imageshown"/>
于 2021-10-04T10:49:17.310 回答
0

可以在文档中找到直接的解决方案: https ://otree.readthedocs.io/en/latest/templates.html#dynamic-images

于 2021-08-19T11:16:18.840 回答