Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 742
RedBaron Avatar asked May 17 '12 08:05

RedBaron


People also ask

How to use filter in Jinja2?

Supported jinja2 filters To use a filter you would typically follow the syntax {{<source_value>|<filter_name>}}. In most cases the <source_value> is likely to be a variable, for example {{givenName|upper}}, although it could be one or more literal values, for example {{ [1, 2, 3, 4]|join }}.

Which of the following is a good use of a Jinja filter?

Jinja2 filter is something we use to transform data held in variables. We apply filters by placing pipe symbol | after the variable followed by name of the filter. Filters can change the look and format of the source data, or even generate new data derived from the input values.

Which of the following is the Jinja syntax that applies three filters on a template variable VAR?

The syntax to apply Jinja filters to template variables is the vertical bar character | , also called a 'pipe' in Unix environments (e.g. {{variable|filter}} ). It's worth mentioning you can apply multiple filters to the same variable (e.g. {{variable|filter|filter}} ).


2 Answers

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
like image 198
ThiefMaster Avatar answered Sep 23 '22 12:09

ThiefMaster


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
like image 42
Tanj Avatar answered Sep 22 '22 12:09

Tanj