开发者

Conditional operator in Mako using Pylons

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.


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

# condition ? trueValue : falseValue
trueValue if condition else falseValue
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜