Adding a custom filter to jinja2 on GAE

I need to add a very simple filter in jinja2. Basically, it takes a number and adds "+" if it is positive. I followed 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 display page):

<div>{{ 123|str_votes }}</div>

This gives me an error: TemplateAssertionError: no filter named 'str_votes'

How to fix it? (There was a similar question here that was never answered.)

+5
source share
2 answers

You need to register a filter. Sort of:

jinja_env.filters['str_votes'] = str_votes
+6
source

I did something similar by registering it in globals:

    def jinja2(self):
       j.environment.globals['humanize_time']= humanize_time
       return j

then calling it with the data we want to pass in the templates, for example:

{{ humanize_time(f.last_post_time) }}
+1
source

All Articles