Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a custom filter to jinja2 on GAE

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.)

like image 722
kennysong Avatar asked Sep 17 '12 17:09

kennysong


2 Answers

You have to register the filter. Something like:

jinja_env.filters['str_votes'] = str_votes
like image 87
voscausa Avatar answered Sep 23 '22 19:09

voscausa


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) }}
like image 29
Paul Collingwood Avatar answered Sep 22 '22 19:09

Paul Collingwood