Search code examples
pythonpyramidmako

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.


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)