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

4

1 回答 1

1

forJinja 中的循环有一个else在没有可用数据时调用的构造。 if也是一个表达式,可用于过滤您的列表。所以这应该工作:

{% 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 %}

唯一需要注意的是,如果有一个以上servprocID 与第 9 个条目匹配,v那么您将获得多个tds - 但如果您只有一个,那么上面的代码就是您要寻找的。

于 2012-02-25T17:51:48.973 回答