[英]Mako templates inline if statement
I have a template variable, c.is_friend, that I would like to use to determine whether or not a class is applied. 我有一个模板变量c.is_friend,我想用它来确定是否应用了一个类。 For example:
例如:
if c.is_friend is True
<a href="#" class="friend">link</a>
if c.is_friend is False
<a href="#">link</a>
Is there some way to do this inline, like: 是否有某种方法可以内联,例如:
<a href="#" ${if c.is_friend is True}class="friend"{/if}>link</a>
Or something like that? 或类似的东西?
Python的正常内联如果有效:
<a href="#" ${'class="friend"' if c.is_friend else ''}>link</a>
You could do it like this: 你可以这样做:
<a href="#"
% if c.is_friend is True:
class="friend"
% endif
>link</a>
{}
inside ${}
! {}
内${}
The solution with the ternary operator mentioned by Jochen is also correct but can lead to unexpected behavior when combining with str.format()
. 使用Jochen提到的三元运算符的解决方案也是正确的,但与
str.format()
结合时可能会导致意外行为。
You need to avoid {}
inside Mako's ${}
, because apparently Mako stops parsing the expression after finding the first }
. 你需要在Mako的
${}
避免使用{}
,因为显然Mako在找到第一个}
后停止解析表达式。 This means you shouldn't use for example: 这意味着您不应该使用例如:
${'{}'.format(a_str)}
. ${'{}'.format(a_str)}
。 Instead use ${'%s' % a_str}
. ${'%s' % a_str}
。 ${'%(first)s %(second)s' % {'first': a_str1, 'second': a_str2}}
. ${'%(first)s %(second)s' % {'first': a_str1, 'second': a_str2}}
。 Instead use ${'%(first)s %(second)s' % dict(first=a_str1, second=a_str2)}
So for example if you need to come up with a more general solution, let's say you need to put a variable called relationship
inside the class tag instead of a static string, you could do it like this with the old string formatting: 因此,例如,如果您需要提出更通用的解决方案,假设您需要在类标记内部而不是静态字符串中放置一个名为
relationship
的变量,您可以使用旧的字符串格式执行此操作:
<a href="#" ${'class="%s"' % relationship if c.has_relation is True else ''}>link</a>
or without string formatting: 或没有字符串格式:
<a href="#"
% if c.has_relation is True:
class="${relationship}"
% endif
>link</a>
This should work for Python 2.7+ and 3+ 这适用于Python 2.7+和3+
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.