2012-03-02 60 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