Mako 模板内联 if 语句

发布于 2024-09-01 12:24:36 字数 351 浏览 2 评论 0原文

我有一个模板变量 c.is_friend,我想用它来确定是否应用某个类。例如:

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

if c.is_friend is False
<a href="#">link</a>

是否有某种方法可以内联执行此操作,例如:

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

或者类似的东西?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

暮色兮凉城 2024-09-08 12:24:36

Python 的正常内联 if 有效:

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

Python's normal inline if works:

<a href="#" ${'class="friend"' if c.is_friend else ''}>link</a>
旧竹 2024-09-08 12:24:36

更通用的解决方案

如果您需要提出更通用的解决方案,假设您需要在类标记内放置一个名为 relationship 的变量而不是静态字符串,您可以使用旧字符串格式:

<a href="#" ${'class="%s"' % relationship if c.has_relation is True else ''}>link</a>

或不带字符串格式:

<a href="#" 
% if c.has_relation is True:
class="${relationship}"
% endif
>link</a>

这应该适用于 Python 2.7+ 和 3+


警告(对于旧版本)

请注意 ${} 内的 {}

Jochen 提到的三元运算符的解决方案也是正确的,但与 str.format() 结合时可能会导致意外行为。

您需要避免 Mako 的 ${} 内的 {},因为显然 Mako 在找到第一个 } 后停止解析表达式。这意味着您不应使用例如:

  • ${'{}'.format(a_str)}。请改用 ${'%s' % a_str}
  • ${'%(第一)s %(第二)s' % {'第一': a_str1, '第二': a_str2}}。而是使用
    ${'%(第一)s %(第二)s' % dict(第一=a_str1, 第二=a_str2)}

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)}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文