无法访问我的jinja2过滤器

时间:2013-08-30 04:48:27

标签: python pyramid jinja2

我查看了文档但找不到答案。这可能是我遗失的基本愚蠢行为。我有jinja2设置w /金字塔,我正在使用pyramid_jinja2并在我的.ini文件中设置我的过滤器:

jinja2.filters =
    model_url = pyramid_jinja2.filters:model_url_filter
    route_url = pyramid_jinja2.filters:route_url_filter
    static_url = pyramid_jinja2.filters:static_url_filter
    my_filter = myapp.view.my_filter

(my_filter只是将每个值乘以100) 这很好用:

@view_config(renderer="json",route_name="tester")
def tester(request):
    myList = [1,2,3,4]
    return render_to_response("templates/test.jinja2",{'myList':myList},request=request)

test.jinja2:

{% for l in myList %}
   {{ l | my_filter }}
{% endfor %}

然而,这不是:

@view_config(renderer="json",route_name="tester")
def tester(request):
    myList = [1,2,3,4]
    tmplate = Template(u'''\
        {% for l in myList %}
           {{ l | my_filter  }}
        {% endfor %}
        ''')
    html = tmplate.render(myList = myList)
    return render_to_response("templates/test.jinja2",{'html':html},request=request)

test.jinja2:

{{ html | safe }}

我的错误讯息:

jinja2.exceptions.TemplateAssertionError
TemplateAssertionError: no filter named 'my_filter'

1 个答案:

答案 0 :(得分:3)

因为您的模板未与环境相关联,所以您通常在哪里定义过滤器。模板类初始化创建自我环境,与主环境无关。

如果你想从字符串动态创建模板,并保留你的过滤器,需要这样的东西:

from jinja2 import Environment

env = Environment() # main environment, basically one per program.
env.filters['my_filter'] = lambda i: i * 100
template = env.from_string('{% for i in myList %}{{ i|my_filter }}_{% endfor %}')
print(template.render(myList=range(10)))
# 0_100_200_300_400_500_600_700_800_900_