I am curious what is the best way to make a function available
throughout all templates?
Here is an example. I wish to add a function `plural` that takes a
number, the singular form and the plural form of a word and returns
either singular or plural.
Then instead of writing ${'singular' if count==1 else 'plural'} I can
write ${plural(count, 'singular', 'plural')}, which makes it much more
readable.
How do I do that?
Sincerely,
P.Krumins
--
You received this message because you are subscribed to the Google Groups "Mako Templates for Python" group.
To post to this group, send email to mako-d...@googlegroups.com.
To unsubscribe from this group, send email to mako-discuss...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/mako-discuss?hl=en.
That's one way--essentially, anything you put into the template
'context' object is available in all templates.
You can also put it (along with perhaps other "helper" type functions)
into it's own template and import them through a namespace...
For example, make a template file "/helpers.mako":
<%def name="plural(cnt,sing,plur=None)"><%
try:
n = int(cnt)
except ValueError:
word = sing
else:
if n == 1:
word = sing
elif plur:
word = plur
elif word.endswith('s'):
word = sing + 'es'
else:
word = sing + 's'
%>${ word }</%def>
and then where ever you want to use it, import it via a namespace
at the top of the template:
<%namespace file="/helpers.mako" name="helpers"/>
and then call it using either:
<%helpers:plural cnt="${n}" sing="foot" plur="feet"/>
or
${ helpers.plural(n, "dragon") }
And of course, another way is to put it into a plain old Python module that
is on your python path, then just import it
<%! import helpers %>
${ helpers.plural(n, "person", "people") }
--
Deron Meranda
http://deron.meranda.us/