Named replaces in strings with Mako
Question
When creating a template in Mako, I would need to write things like : ${_('Hello, %(fname)s %(lname)s') % {'fname':'John','lname':'Doe'}}
I keep getting SyntaxException: (SyntaxError) unexpected EOF while parsing when writing that. Is there wny way to do the same ?
${_('Hello, %s %s') % ('John', 'Doe')}
works, but it does not allow to change the order of the replacements when changing language, if needed.
Thanks.
Solution
Try the new Python string formatting:
>>> "{foo} {bar}".format(foo="foo", bar="bar")
'foo bar'
>>> "{foo} {bar}".format(**{"foo": "Hello", "bar": "World!"})
'Hello World!'
It looks nicer and is futureproof.
OTHER TIPS
Using {}
inside Mako's ${}
is complicated; apparently Mako stops parsing the expression after finding the first }
. A possible workaround is to use dict()
instead of {}
:
${_('Hello, %(fname)s %(lname)s') % dict(fname='John', lname='Doe')}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow