Pyramid Chameleon Tal:条件'不'问题

时间:2013-07-16 01:39:40

标签: pyramid template-engine chameleon template-tal

我正在尝试在Pyramid Chameleon模板中显示条件文本。基本上,检查字典键'maxed_out_alerts'是否为空(false)或字符串为'yes'。

<p tal:condition="not:maxed_out_alerts"><h3>Maxed Out.</h3></p>
<p tal:condition="maxed_out_alerts"><h3>Not Maxed Out</h3></p>

当'maxed_out_alerts'为空字符串时,仅显示(正确)'Maxed Out'。但是,如果'maxed_out_alerts'包含'yes'字符串,则会显示(Maxed Out)和“Not Maxed Out”(错误)。

似乎NOT总是被评估为真实条件。它应该显示一条或另一条消息,而不是两条消息。我究竟做错了什么?感谢

2 个答案:

答案 0 :(得分:3)

对于python中的TAL条件,你可以说python:然后使用python语法条件

<p tal:condition="python:len(maxed_out_alerts) > 0"><h3>Maxed Out.</h3></p>

答案 1 :(得分:1)

如果将布尔状态保存在布尔变量中,它可能会有所帮助。通过将此信息存储在字符串中,您遇到了您现在面临的问题。这就是内置的python类型 - 使用它们。

作为金字塔开发人员,我建议将逻辑移动以将maxed_out_alerts的当前值评估为字符串中的视图方法,并将字典中的计算字符串传递给渲染器/模板。这样你甚至可以为视图逻辑创建测试 - 任何金字塔教程,简单或高级教程都会告诉你如何做到这一点。

任何简单逻辑的良好开端 - 假设逻辑变得更复杂,或者您甚至必须翻译模板的文本。

@view_config(name="yourname", renderer='templates/yourtemplate.pt')
def myview(request):
    """
    #get boolean state from model
    #could be that you want to have it the other way round
    #or do it by using python ternary operator - a if test else b 
    if model['maxed_out_alerts'] == True:
        maxed_out_alerts = 'Maxed Out'
    else:
        maxed_out_alerts = 'Not Maxed Out'


    return dict(maxed_out_alerts = maxed_out_alerts)

在你的模板中

<h3 tal:content="maxed_out_alerts">text for maxed out alerts</h3>

<h3>${maxed_out_alerts}</h3>