【问题标题】:loading page content from .txt file breaks Django template system从 .txt 文件加载页面内容会破坏 Django 模板系统
【发布时间】:2012-03-20 16:36:09
【问题描述】:

在我的 python Google App Engine 应用程序中,我的大多数页面的设计都是相同的,因此我创建了 page.html 作为基本模板。每个单独页面的内容都在一个 .txt 文件中。在我的 .py 脚本中,我这样做:

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 get(self):

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

【问题讨论】:

  • 什么,你为什么不使用包含模板标签?您可以发布您的视图代码吗?和模板?
  • 等等,你让我大吃一惊。我不知道那个标签,查一下。感谢您的快速回复
  • 我想我正在使用包含模板标签,对吧?我正在按照 GAE 文档中的说明进行操作:code.google.com/appengine/docs/python/gettingstarted/… - 所有相关的视图代码都在上面发布。它只是简单的 django 模板变量 {{like this}} 没有在我的模板中被替换,因为包含它们的内容本身就是 {{one of these}} 所以它们不会被解析。
  • 你也可以使用模板继承。至于精确的“如何”,我应该看到你的视图和模板代码。

标签: python django google-app-engine templates


【解决方案1】:

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

此示例包含模板“foo/bar.html”的内容:

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

此示例包括名称包含在变量 template_name 中的模板的内容:

{% include template_name %}

【讨论】:

猜你喜欢
  • 2017-04-20
  • 2015-12-21
  • 1970-01-01
  • 2014-03-09
  • 1970-01-01
  • 2013-12-30
  • 2015-12-19
  • 2011-11-27
  • 2016-12-03
相关资源
最近更新 更多