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. 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<开发者_Python百科;/a>
Or something like that?
Python's normal inline if works:
<a href="#" ${'class="friend"' if c.is_friend else ''}>link</a>
More General Solution
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:
<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+
WARNING (for older versions)
Pay attention to the {}
inside ${}
!
The solution with the ternary operator mentioned by Jochen is also correct but can lead to unexpected behavior when combining with str.format()
.
You need to avoid {}
inside Mako's ${}
, because apparently Mako stops parsing the expression after finding the first }
. This means you shouldn't use for example:
${'{}'.format(a_str)}
. Instead use${'%s' % a_str}
.${'%(first)s %(second)s' % {'first': a_str1, 'second': a_str2}}
. Instead use
${'%(first)s %(second)s' % dict(first=a_str1, second=a_str2)}
精彩评论