2011-07-12 16 views
2

是否可以使用不帶文件路徑的template.render()?使用不帶文件引用的template.render()

我想爲我的數據存儲區中的文本屬性執行動態字符串replacemnt。立刻想到模板化。也許還有另一種方式?我的想法是以下...

my_string = template.render(my_model.description,template_dict) 
+0

剛剛找到string.Template。這可能是最好的答案,不是嗎? – Greg

+0

還有簡單的舊字符串格式:''a%s b「%some_str'。新的字符串格式「'a {0} b」'只適用於Python 2.6,而App Engine使用2.5。 –

+0

理想情況下,它將很像使用字典的webapp模板。任意字符串替換不太靈活。這將是理想的......「你好,{{name}},你很酷。」 {'name':'超人'} – Greg

回答

1

從「google-app-engine」標籤判斷,我假設你正在談論google.appengine.ext.webapp提供的模板引擎?根據documentation:「爲了您的方便,webapp模塊包含了Django的模板引擎」。因此,有看看Django docs for templates ......

據我所知,你應該能夠做到像下面這樣(我假設my_model.description包含你的模板字符串):

t = template.Template(my_model.description) 
my_string = t.render(template.Context(template_dict)) 

(看看template.py的webapp代碼也可能有用)

+1

這將工作,除非模板字符串包含將要加載其他模板的標籤。 –

+0

謝謝你提及(我實際上不熟悉django模板;-))。我不知道OP是否會這樣做。如果他這樣做,我想應該有可能提供你自己的「裝載機」? (但我會把它留給你;-),或者至少有一些對此有更多經驗的人) – Steven

0

有沒有官方支持的方式做使用與web應用程序的template.render()

這裏非基於文件的模板的,與1.5.1工作的不受支持方式(而且可能工作之後):

class StringTemplate(webapp.RequestHandler): 
    def get(self): 
    import django.template 
    mytemplate = "<html>...</html>" 
    t = django.template.Template(mytemplate) 
    fake_path = os.path.abspath("main.py") # or any uploaded file 
    template.template_cache[fake_path] = t 
    self.response.out.write(template.render(fake_path, {}) 

app.yaml被使用,因爲模板緩存使用templa的絕對路徑te作爲關鍵字,所以任何真實的文件都會作爲假模板來源。但是這是一個可能改變的實現細節。

+0

app.yaml不是App Engine上的真實文件;它不會與應用程序一起上傳。 – geoffspear

+0

適用於dev_appserver!謝謝,固定在上面。 –