Question

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</a>

Or something like that?

Was it helpful?

Solution

Python's normal inline if works:

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

OTHER TIPS

Easy Solution

You could do it like this:

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

WARNING

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)}

General Solution

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:

<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+

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top