在 Pyramid 视图上动态加载 jinja2 模板
Load jinja2 templates dynamically on a Pyramid view
我正在开发 Pyramid project with jinja2 templating engine. Following the jinja2 documentation I've find out a way to load different templates from a unique view. But taking into account that the module pyramid_jinja2 我的应用程序中已经配置了模板的默认路径。我想知道是否有另一种更优雅的方式来完成这项工作。这是我的方法:
from jinja2 import Environment, PackageLoader
@view_config(context=Test)
def test_view(request):
env = Environment(loader=PackageLoader('project_name', 'templates'))
template = env.get_template('section1/example1.jinja2')
return Response(template.render(data={'a':1,'b':2}))
我能否从某处获取 pyramid_jinja2 环境的实例,这样我就不必在视图中再次设置模板的默认路径?
以下就够了:
from pyramid.renderers import render
template = "section/example1.jinja2"
context = dict(a=1, b=2)
body = render(template, context, request=request)
并在 __init__.py
:
中配置加载
config.add_jinja2_search_path('project_name:templates', name='.jinja2', prepend=True)
我正在开发 Pyramid project with jinja2 templating engine. Following the jinja2 documentation I've find out a way to load different templates from a unique view. But taking into account that the module pyramid_jinja2 我的应用程序中已经配置了模板的默认路径。我想知道是否有另一种更优雅的方式来完成这项工作。这是我的方法:
from jinja2 import Environment, PackageLoader
@view_config(context=Test)
def test_view(request):
env = Environment(loader=PackageLoader('project_name', 'templates'))
template = env.get_template('section1/example1.jinja2')
return Response(template.render(data={'a':1,'b':2}))
我能否从某处获取 pyramid_jinja2 环境的实例,这样我就不必在视图中再次设置模板的默认路径?
以下就够了:
from pyramid.renderers import render
template = "section/example1.jinja2"
context = dict(a=1, b=2)
body = render(template, context, request=request)
并在 __init__.py
:
config.add_jinja2_search_path('project_name:templates', name='.jinja2', prepend=True)