Mako, use if / else control structure in one line

Question:

I would like to do something like this, restricted on on line. I can’t use multi line.

% if object.lang == 'fr_FR': 'Rappel de paimenet' % else: 'Payment reminder' %endif

I know that this is not the good syntax, but I did find in the documentation how I coiuld manage to do it ?

Cheers

Asked By: renard

||

Answers:

I don’t think you can do this with Mako, at least not in the way you want.

The % can appear anywhere on the line as long as no text precedes it;

One way you can do this is to not put the if-statement in the template. It seems you are trying to use a translation, so make the translation in the code you are using to feed the template:

text = 'Rappel de paimenet' if object.lang == 'fr_FR' else 'Payment reminder'
# Now your template doesn't need to use an if-statement
template = Template("""Status: {{text}}""").render(text=text)

Since it appears that you are using this for translations, I would look into using gettext and Babel. If you are using this in a web application, look into any translation-specific utilities (such as django-babel or flask-babel).

Answered By: Mark Hildreth

You can do this in pure python.

var = {True: newValueIfTrue, False: newValueIfFalse}[condition]

It should be easy to wrap it in a template.

Answered By: Ali Rasim Kocal
${object.lang == 'fr_FR' and 'Rappel de paimenet' or 'Payment reminder'}

Or if you want to extend it to more languages, with english as the default:

${{'fr_FR': 'Rappel de paimenet', 'es_ES': ...}.get(object.lang, 'Payment reminder')}
Answered By: patstew

We need to use "n":

tmpl = "% if object.lang == 'fr_FR':n 'Rappel de paimenet'n  % else:n 'Payment reminder'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="test.tmpl", output_encoding='utf-8')
result = t2.render(object.lang="English").decode("unicode_escape")
print(result)
Answered By: somenxavier
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.