0

I have this template in Mako templating system:

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. I tried put new line with \ but it did not work:

tmpl = """% if name:\ Hello ${name} \ % else:\ Hello world\ % endif"""
somenxavier
  • 1,206
  • 3
  • 20
  • 43
  • I discovered it is a duplicated of [this](https://stackoverflow.com/questions/21633028/mako-use-if-else-control-structure-in-one-line). Can anyone mark this question as duplicated? – somenxavier Jan 16 '23 at 18:42

1 Answers1

0

We need to use "\n":

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

If we use file template, we need to expand "\n". As commented in this post and unicode Chapter in official Mako documentation, one solution could be:

t2 = Template(filename="prova.tmpl", output_encoding='utf-8')
result = t2.render(name="Me").decode("unicode_escape")
print(result)
somenxavier
  • 1,206
  • 3
  • 20
  • 43