2013-03-19 107 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

相關問題