1

I am having a variable scope issue in Jinja that is misaligning a table. I am trying to convert the current template that is written in Cheetah to Jinja but for some reason this block of logic does not translate and getting the output the python is an even bigger mess.

Original cheetah code

#set $sname = ""
#for $serv in $proc:
    #if $serv.id == $v[8]:
        <td> $serv.shortname </td>
        #set $sname = $serv.shortname
    #end if
#end for

#if $sname == "":
<td><span style="color:#ff0000">Server not found</span></td>
#end if

So the desired output of the code above is loop through some objects match the ids to the current row object and update the value. then check if the value is still null and print no server found instead.

Jinja Code that doesnt work

{% set sname = "" %}
{{ v[8] }}
{% for serv in proc %}
{% if serv.id == v[8] %}
    <td> {{ serv.shortname }} </td>
    {% set sname = serv.shortname %}
{% endif %}
{% endfor %}

{% if sname == "" %}
<td><span style="color:#ff0000">Server not found</span></td>
{% endif %} 

This code instead if it correctly matches the ids it prints both columns because outside of the loop the sname is still set to "". I tried doing the comparison inside the loop but it printed something like

Server Not found | ServerName | Server not found

Community
  • 1
  • 1
BillPull
  • 6,853
  • 15
  • 60
  • 99
  • Similar question addressing scope in Jinja2 templates: http://stackoverflow.com/questions/4870346/can-a-jinja-variables-scope-extend-beyond-in-an-inner-block – robots.jpg Feb 24 '12 at 21:08

1 Answers1

1

The for loop in Jinja has an else construct that is called when no data is available. if is also an expression, and can be used to filter your list. So this should work:

{% for serv in proc if serv.id == v[8] %}
    <td> {{ serv.shortname }} </td>
{% else %}
    <td><span style="color:#ff0000">Server not found</span></td>
{% endfor %}

The only thing to note is that if there is more than one serv in proc with an ID that matches the 9th entry in v then you will get multiple tds - but if you will only ever have one then the above code is what you are looking for.

Sean Vieira
  • 155,703
  • 32
  • 311
  • 293