Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jinja2 Custom filter "TemplateAssertionError: no filter named 'format_number'"

I'm getting the "TemplateAssertionError: no filter named 'format_number'" error, when trying to register a custom filter on the template environment by updating the filters dict on the environment.

In my module, I have imported environment module as follows:

from jinja2 import environment 

In my class I defined the following method:

class DashboardHandler(SecurePageHandler):

   def format_number(number):
        s = '%d' % number
        groups = []
        while s and s[-1].isdigit():
            groups.append(s[-3:])
            s = s[:-3]
        return s + ','.join(reversed(groups))

    def do_get(self):
            # ... snip ...
            env = environment.Environment(self)
            env.filters['format_number'] = self.format_number
            # ... snip ...

Inside my html template file I tried to implement the filter as follows:

{{top_five_url .total|format_number}}

How is this happening?

Is there a default environment instance, we should use?

like image 394
chinthakad Avatar asked Dec 01 '11 10:12

chinthakad


1 Answers

I could resolve my problem as follow,

Inside the module, I defined my method and updated the filters dictionary globally as follows:

import jinja2

def format_number(number):
    s = '%d' % number
    groups = []
    while s and s[-1].isdigit():
        groups.append(s[-3:])
        s = s[:-3]
    return s + ','.join(reversed(groups))

jinja2.filters.FILTERS['format_number'] = format_number
like image 68
chinthakad Avatar answered Oct 24 '22 18:10

chinthakad