oTree:如何根据变量的值显示特定的.jpg条件?

2024-10-04 09:28:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个条件变量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. 在javascript中使用if/else:

    {{ 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代码试图简单地加载“ImageShowed”


Tags: gtsrcimgifvarhtmltagstatic
2条回答

我不确定你的oTree是什么版本。对于oTree<;5.对于pages.py的_模板,应在vars_中返回条件_var。在模板中,尝试以下操作

<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"/>

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

相关问题 更多 >