【问题标题】:Mako templates inline if statementMako 模板内联 if 语句
【发布时间】:2011-02-19 23:25:30
【问题描述】:

我有一个模板变量 c.is_friend,我想用它来确定是否应用了一个类。例如:

if c.is_friend is True
<a href="#" class="friend">link</a>

if c.is_friend is False
<a href="#">link</a>

有什么办法可以内联,比如:

<a href="#" ${if c.is_friend is True}class="friend"{/if}>link</a>

或者类似的?

【问题讨论】:

    标签: python templates mako


    【解决方案1】:

    Python 的正常内联如果有效:

    <a href="#" ${'class="friend"' if c.is_friend else ''}>link</a>
    

    【讨论】:

    • +1,可惜没有比将 HTML 标记放在 Python 字符串中更好的方法了...
    • 如果能把无意义的“else”case去掉就更好了。
    • 这也有引用的问题。 ${'value="+val+"' if val is not None else ''} 不起作用(您需要保留 " 的部分和引用 html 字符的部分)。
    • @kratenko 你可以使用str.format() 来解决一些问题
    • @IanHunter 我在使用 str.format() 时遇到了一些问题,因为在 Mako 的 ${} 中使用 {} 很复杂;显然 Mako 在找到第一个 } 后停止解析表达式。
    【解决方案2】:

    更通用的解决方案

    如果您需要提出一个更通用的解决方案,假设您需要在类标签中放置一个名为 relationship 的变量而不是静态字符串,您可以使用旧的字符串格式这样做:

    <a href="#" ${'class="%s"' % relationship if c.has_relation is True else ''}>link</a>
    

    或者没有字符串格式:

    <a href="#" 
    % if c.has_relation is True:
    class="${relationship}"
    % endif
    >link</a>
    

    这应该适用于 Python 2.7+ 和 3+


    警告(旧版本)

    注意{}里面的${}

    Jochen 提到的使用三元运算符的解决方案也是正确的,但在与str.format() 结合时会导致意外行为。

    您需要避免在 Mako 的 ${} 中使用 {},因为显然 Mako 在找到第一个 } 后停止解析表达式。这意味着您不应该使用例如:

    • ${'{}'.format(a_str)}。请改用${'%s' % a_str}
    • ${'%(first)s %(second)s' % {'first': a_str1, 'second': a_str2}}。改为使用
      ${'%(first)s %(second)s' % dict(first=a_str1, second=a_str2)}

    【讨论】:

    • 我在 mako 模板中使用了这一行没有任何问题,所以也许他们已经解决了 ${} 中的 {} 的问题:${f"{metric + ':':41} {score:{score_format}}"}
    猜你喜欢
    • 2011-10-01
    • 1970-01-01
    • 2017-10-28
    • 1970-01-01
    • 1970-01-01
    • 2014-11-21
    • 1970-01-01
    • 1970-01-01
    • 2013-02-15
    相关资源
    最近更新 更多