2013-03-19 100 views
2

我目前正在使用金字塔web框架并使用Mako模板进行配置。我知道我可以在视图方法(Pyramid - Is it possible to render my mako template as a string within my view callable?)中将模板呈现为字符串,但是,我想知道是否可以从视图中获取实际的模板对象,而不仅仅是用于呈现模板的函数。从金字塔应用程序视图中获取Mako模板

翻阅金字塔源代码,在mako_templating.py我看到默认的TemplateLookup类被Pyramid的查找方法覆盖。无论如何访问这个查找对象主要是因为我可以使用get_template函数是它的一部分吗?

谢谢你在这个问题上的任何方向。

回答

4

Pyramid的渲染API没有正式支持这种内省级别。这就是说,这是一个办法。这是完全没有记录,不支持,私人等,等等。意思是,不要抱怨,当这停止工作。

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) 
+0

谢谢你的回答,Michael!最后,我决定使用项目配置设置来实现单独的Mako Templatelookup实例。 – 2013-03-22 19:26:52

0

这个工作对我来说:

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

一个例子使用情况是这样的:

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

通过下面的一行在金字塔的设置文件:

mako.directories = your_app:templates 

模板te取自your_app/templates/email/welcome_message.html。所有inheritanceinclude标记的工作方式与渲染为视图响应的模板一样。

+0

虽然这可行,但我的问题是使用已经为应用程序配置的TemplateLookup实例。像这样调用render函数并没有考虑到现有的模板配置。 – 2015-06-09 16:52:34

相关问题