Ander
Ander

Reputation: 5634

Load jinja2 templates dynamically on a Pyramid view

I'm developing a 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 was already configured in my app with a default path for templates. I was wondering if there is another way more elegant to get this done. This is my approach:

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}))

Can I get an instance of the pyramid_jinja2 environment from somewhere so I don't have to set again the default path for templates in the view?

Upvotes: 1

Views: 571

Answers (1)

Mikko Ohtamaa
Mikko Ohtamaa

Reputation: 83358

The following is enough:

  from pyramid.renderers import render

  template = "section/example1.jinja2"
  context = dict(a=1, b=2)
  body = render(template, context, request=request)

And to configure loading do in your __init__.py:

  config.add_jinja2_search_path('project_name:templates', name='.jinja2', prepend=True)

Upvotes: 1

Related Questions