简体   繁体   English

在一行中使用 mako 模板创建条件

[英]Make a conditional in mako template in one line

I have this template in Mako templating system :我在Mako 模板系统中有这个模板:

from mako.template import Template

tmpl = """
% if name:
Hello ${name}
% else:
Hello world
% endif
"""

t = Template(tmpl)
t.render(name="Me")

I want to modify template to have simply one line conditional.我想将模板修改为只有一行条件。 Something like this (in jinja syntax):像这样的东西(在神社语法中):

Hello {% if name %} {{name}} {% else %} world {% endif %}

It seems like Mako needs a line before control structures.似乎 Mako 在控制结构之前需要一行。 I tried put new line with \ but it did not work:我尝试\换行,但没有用:

tmpl = """% if name:\ Hello ${name} \ % else:\ Hello world\ % endif"""

We need to use "\n":我们需要使用“\n”:

tmpl = "% if name:\n Hello ${name}\n % else:\n Hello world\n % endif"

If we use file template, we need to expand "\n".如果我们使用文件模板,我们需要扩展“\n”。 As commented in this post and unicode Chapter in official Mako documentation , one solution could be:正如这篇文章unicode Chapter in official Mako documentation 中所评论的那样,一种解决方案可能是:

t2 = Template(filename="prova.tmpl", output_encoding='utf-8')
result = t2.render(name="Me").decode("unicode_escape")
print(result)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM