RedBaron
RedBaron

Reputation: 4755

Adding a custom filter to jinja2 under pyramid

This question has been asked before but the accepted solution (given by the question poster himself) says that we can add the new filter to jinja2.filter.FILTER straightaway.

But in the jinja2 documentation, it is advised that the filter be added to the environment.

I am developing an app under pyramid and need to define my custom filter and do the following.

from jinja2 import Environment

#Define a new filter
def GetBitValue(num,place):
    y = (num >> (place-1)) & 1
    return y

env = Environment()
env.filters['getbitvalue'] = GetBitValue

Where should this code fragment be placed?

I tried placing it in the views file but that obviously did not work.

If i place it in __init__.py, how do I make sure that jinja2 picks it up? I mean how do I send back the env to jinja2 settings under pyramid?

Upvotes: 5

Views: 3765

Answers (2)

Tanj
Tanj

Reputation: 1354

For completeness this would be how you register the filter in code.

# __init__.py
def main(global_config, **settings):
    #....
    config = Configurator(settings=settings)
    config.include('pyramid_jinja2')
    config.commit() # this is needed or you will get None back on the next line
    jinja2_env = config.get_jinja2_environment()
    jinja2_env.filters['getbitvalue'] = GetBitValue

Upvotes: 6

ThiefMaster
ThiefMaster

Reputation: 318488

Assuming you are using pyramid_jinja2, you can use pyramid_jinja2.get_jinja2_environment() via the configurator instance to access the environment.

However, apparently you can also register them via the pyramid config file without accessing the env directly:

[app:yourapp]
    # ... other stuff ...
    jinja2.filters =
        # ...
        getbitvalue = your_package.your_subpackage:GetBitValue

Upvotes: 11

Related Questions