views:

123

answers:

1

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.

+2  A: 

If it's running Python, the "ternary operator" is

# condition ? trueValue : falseValue
trueValue if condition else falseValue
KennyTM
Yes, thanks!${' selected="selected"' if blah == 1 | n} works great.${' selected="selected"' if blah == 1 else ' something-else' | n} also works great.
Antoine Leclair