Python jinja2 模块,contextfilter() 实例源码

我们从Python开源项目中,提取了以下4个代码示例,用于说明如何使用jinja2.contextfilter()

项目:kayobe    作者:stackhpc    | 项目源码 | 文件源码
def _make_attr_filter(attr):
    @jinja2.contextfilter
    def func(context, name, inventory_hostname=None):
        return net_attr(context, name, attr, inventory_hostname)
    return func
项目:aiohttp-devtools    作者:aio-libs    | 项目源码 | 文件源码
def reverse_url(context, name, **parts):
    """
    jinja2 filter for generating urls,
    see http://aiohttp.readthedocs.io/en/stable/web.html#reverse-url-constructing-using-named-resources

    Usage:
    {%- raw %}

      {{ 'the-view-name'|url }} might become "/path/to/view"

    or with parts and a query

      {{ 'item-details'|url(id=123, query={'active': 'true'}) }} might become "/items/1?active=true
    {%- endraw %}

    see app/templates.index.jinja for usage.

    :param context: see http://jinja.pocoo.org/docs/dev/api/#jinja2.contextfilter
    :param name: the name of the route
    :param parts: url parts to be passed to route.url(), if parts includes "query" it's removed and passed seperately
    :return: url as generated by app.route[<name>].url(parts=parts, query=query)
    """
    app = context['app']

    kwargs = {}
    if 'query' in parts:
        kwargs['query'] = parts.pop('query')
    if parts:
        kwargs['parts'] = parts
    return app.router[name].url(**kwargs)
项目:aiohttp-devtools    作者:aio-libs    | 项目源码 | 文件源码
def static_url(context, static_file_path):
    """
    jinja2 filter for generating urls for static files. NOTE: heed the warning in create_app about "static_root_url"
    as this filter uses app['static_root_url'].

    Usage:

    {%- raw %}
      {{ 'styles.css'|static }} might become "http://mycdn.example.com/styles.css"
    {%- endraw %}

    see app/templates.index.jinja for usage.

    :param context: see http://jinja.pocoo.org/docs/dev/api/#jinja2.contextfilter
    :param static_file_path: path to static file under static route
    :return: roughly just "<static_root_url>/<static_file_path>"
    """
    app = context['app']
    try:
        static_url = app['static_root_url']
    except KeyError:
        raise RuntimeError('app does not define a static root url "static_root_url"')
    return '{}/{}'.format(static_url.rstrip('/'), static_file_path.lstrip('/'))
# {% endif %}


# {% if database.is_pg_sqlalchemy %}
项目:websauna    作者:websauna    | 项目源码 | 文件源码
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)