def include_filter(config:Configurator, name:str, func: t.Callable, renderers=(".html", ".txt",)):
"""Register a new Jinja 2 template filter function.
Example::
import jinja2
@jinja2.contextfilter
def negative(jinja_ctx:jinja2.runtime.Context, context:object, **kw):
'''Output the negative number.
Usage:
{{ 3|neg }}
'''
neg = -context
return neg
Then in your initialization:::
include_filter(config, "neg", negative)
:param config: Pyramid configurator
:param name: Filter name in templates
:param func: Python function which is the filter
:param renderers: List of renderers where the filter is made available
"""
def _include_filter(name, func):
def deferred():
for renderer_name in renderers:
env = config.get_jinja2_environment(name=renderer_name)
assert env, "Jinja 2 not configured - cannot add filters"
env.filters[name] = func
# Because Jinja 2 engine is not initialized here, only included here, we need to do template filter including asynchronously
config.action('pyramid_web-include-filter-{}'.format(name), deferred, order=1)
_include_filter(name, func)
评论列表
文章目录