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?
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 }}.
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.
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}} ).
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With