I need to add a very simple filter to jinja2. Basically, it takes a number and appends a '+' if it's positive. I followed the jinja2 docs on how to add custom filters, but it doesn't seem to work (on GAE).
Python:
def str_votes(votes):
if votes > 0:
return '+' + str(votes)
else:
return str(votes)
# jinja2 stuff
template_dir = os.path.join(os.path.dirname(__file__), 'templates')
jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir),
autoescape=True)
jinja_env.globals['str_votes'] = str_votes
HTML (for rendered page):
<div>{{ 123|str_votes }}</div>
This gives me an error of: TemplateAssertionError: no filter named 'str_votes'
How do I fix this? (There was a similar question here that was never answered.)
You have to register the filter. Something like:
jinja_env.filters['str_votes'] = str_votes
I've done something similar by registering it in the globals:
def jinja2(self):
j.environment.globals['humanize_time']= humanize_time
return j
then calling it with the data we want to pass it in the templates like so:
{{ humanize_time(f.last_post_time) }}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With