Adding a custom filter to jinja2 under the pyramid

This question has been asked before , but the decision made (given by the author of the question) says that we can add a new filter to jinja2.filter.FILTER right now.

But in jinja2 documentation , it is recommended to add a filter to the environment.

I am developing an application under a pyramid and must 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 piece of code be placed?

I tried to put it in a views file, but that obviously didn't work.

If I put it in __init__.py, how can I make sure jinja2 picks it up? I mean, how do I send settings envto jinja2 under the pyramid?

+5
source share
2

, pyramid_jinja2, pyramid_jinja2.get_jinja2_environment() configurator .

, -, env:

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

, .

# __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
+5

All Articles