oTree: How to display a certain .jpg conditional on a variable's value?

Viewed 365

I have a condition variable player.condition_var which can have the integer values 1, 2 or 3.

Now I want to display either 1.jpg, 2.jpg or 3.jpg on the Results.html page conditional on the value of the variable. But I don't get it to work. How can it be done?

What I've tried so far:

  1. Simply include the oTree variable in the HTML tag: <img src="{{static "folder/{{ player.condition_var }}.jpg" }}"/>

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

  2. Use if/else with 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" }}"/>
    

    => The image cannot be loaded. The variable seems to not get filled with one of the paths. Thus, the HTML code tries to simply load "imageshown"

2 Answers

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