2012-03-02 54 views
2

在我的python Google App Engine應用程序中,我的大多數頁面的設計都是相同的,所以我創建了page.html作爲基本模板。每個單獨頁面的內容都在.txt文件中。在我的.py腳本我這樣做:從.txt文件中下載頁面內容Django模板系統

pageFile = open("content.txt", "r") 
pageText = pageFile.read(); 
pageFile.close() 

然後將此

template_values = { 
    'full_name': full_name, 
    'notification': notification, 
    'pageText': pageText 
    } 

    path = os.path.join(os.path.dirname(__file__), 'page.html') 

當頁面呈現的pageText內容不會獲取插入,但Django的模板標記(例如{{FULL_NAME}} )不會被分析。這是我的問題。我懷疑這個解決方案是渲染HTML文件兩次,一次加載內容和一次解析Django模板的東西,但我找不到任何資源如何做到這一點。任何幫助讚賞。

編輯:具體看代碼

指令頁

類指令(webapp.RequestHandler): DEF得到(個體經營):

checkUser(self) 
    checkProfile(self) 
    flowControl(self, 0) 

    prepareHeader(self) 

    global notification 

    try: 
     notification 
    except NameError: 
     notification = "" 

    pageFile = open("instruction.txt", "r") 
    pageText = pageFile.read(); 
    pageFile.close() 

    template_values = { 
     'url': url, 
     'url_linktext': url_linktext, 
     'user': user, 
     'pageText': pageText, 
     'footerText': footerText, 
     'notification': notification 
    } 

    global instruction, refresh 
    instruction = True 
    refresh = True 

    path = os.path.join(os.path.dirname(__file__), 'instruction.html') 
    self.response.out.write(template.render(path, template_values)) 
+0

什麼,爲什麼你不使用包含模板標籤?你能發佈你的視圖代碼嗎?和模板? – jpic 2012-03-02 06:11:32

+0

等一下,你在想我。我不知道那個標籤,查找它。感謝您的快速回復 – Tr3y 2012-03-02 06:12:07

+0

我想我正在使用包含模板標記,對嗎?我按照GAE文檔中的說明執行操作:http://code.google.com/appengine/docs/python/gettingstarted/templates.html - 上面列出了所有相關的視圖代碼。這只是簡單的django模板變量{{像這樣}},它們不會在我的模板中被替換,因爲包含它們的內容本身就是{{其中一個}},所以它們不會被解析。 – Tr3y 2012-03-02 06:19:39

回答

2

可以使用Django include template tag。或者template inheritance

此示例包括模板爲「foo /一個bar.html」的內容:

{% include "foo/bar.html" %} 

此示例包括其名稱包含在可變TEMPLATE_NAME模板的內容:

{% include template_name %} 
+0

你是男人!感謝您幫助初學者。 – Tr3y 2012-03-02 06:30:17

+0

實際上,模板繼承可能是一個更好的選擇,但沒有你的代碼,我不能依靠展示你比文檔更好。 https://docs.djangoproject.com/en/dev/topics/templates/ – jpic 2012-03-02 06:40:56