Conditional operator in Mako using Pylons
Posted
by Antoine Leclair
on Stack Overflow
See other posts from Stack Overflow
or by Antoine Leclair
Published on 2010-05-21T18:48:05Z
Indexed on
2010/05/21
19:20 UTC
Read the original article
Hit count: 271
In PHP, I often use the conditional operator to add an attribute to an html element if it applies to the element in question. For example:
<select name="blah">
<option value="1"<?= $blah == 1 ? ' selected="selected"' : '' ?>>
One
</option>
<option value="2"<?= $blah == 2 ? ' selected="selected"' : '' ?>>
Two
</option>
</select>
I'm starting a project with Pylons using Mako for the templating. How can I achieve something similar? Right now, I see two possibilities that are not ideal.
Solution 1:
<select name="blah">
% if blah == 1:
<option value="1" selected="selected">One</option>
% else:
<option value="1">One</option>
% endif
% if blah == 2:
<option value="2" selected="selected">Two</option>
% else:
<option value="2">Two</option>
% endif
</select>
Solution 2:
<select name="blah">
<option value="1"
% if blah == 1:
selected="selected"
% endif
>One</option>
<option value="2"
% if blah == 2:
selected="selected"
% endif
>Two</option>
</select>
In this particular case, the value is equal to the variable tested (value="1" => blah == 1), but I use the same pattern in other situations, like <?= isset($variable) ? ' value="$variable" : '' ?>
.
I am looking for a clean way to achieve this using Mako.
© Stack Overflow or respective owner