Question

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.

Was it helpful?

Solution

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)

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top