Get Mako template from within Pyramid app view

I'm currently using the Pyramid web framework and I have it configured with Mako templates. I know that I can render a template as a string from within a view method (Pyramid - Is it possible to render my mako template as a string within my view callable?), however, I was wondering if it is possible to get the actual template object from within a view and not just a function to render the template.

Looking through the Pyramid source code, in mako_templating.py I see that the default TemplateLookup class is overridden with a lookup method for Pyramid. Is there anyway to access this lookup object primarily so I can use the get_template function that is part of it?

Thanks for any direction on this issue.


This level of introspection is not officially supported by Pyramid's rendering API. That being said, here's a way to do it. This is completely undocumented, unsupported, private, etc, etc. Meaning, don't come complaining when this stops working.

from pyramid.mako_templating import IMakoLookup
lookup = request.registry.queryUtility(IMakoLookup, name='mako.')
tmpl = lookup.get_template('myapp:templates/foo.mako')

opts = {} # rendering context
result = tmpl.render_unicode(**opts)

This works for me:

from pyramid.renderers import render
sRenderedStuff = render('path/to/template.mak',dContext)

An example use case would be something like this:

sEmailHtml = render("email/welcome_message_html.mak",dContext)

With the following line in your pyramid settings file:

mako.directories = your_app:templates

The template is fetched from your_app/templates/email/welcome_message.html . All inheritance and include tags work just as they would for templates rendered to a view response.

链接地址: http://www.djcxy.com/p/69092.html

上一篇: 每种方法分开的权限

下一篇: 从金字塔应用程序视图中获取Mako模板