【问题标题】:Using template.render() without a file reference在没有文件引用的情况下使用 template.render()
【发布时间】:2011-07-12 20:02:15
【问题描述】:

是否可以在没有文件路径的情况下使用 template.render() ?

我想为我的数据存储中的文本属性执行动态字符串替换。模板立即浮现在脑海中。也许还有另一种方法?我的想法如下……

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

【问题讨论】:

  • 刚刚找到 string.Template。这可能是最好的答案,不是吗?
  • 还有简单的旧字符串格式:"a %s b" % some_str。新的字符串格式 "a {0} b" 仅在 Python 2.6 中提供,而 App Engine 使用 2.5。
  • 理想情况下,它的行为很像使用字典的 webapp 模板。任意字符串替换不太灵活。这将是理想的......“你好,{{name}}。你很酷。” {'name':'超人'}
  • 是的,我认为 string.Template 是你最好的选择。

标签: python google-app-engine template-engine


【解决方案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 代码可能也很有用)

【讨论】:

  • 除非模板字符串包含要加载其他模板的标签,否则它会起作用。
  • 感谢您提及(我实际上并不熟悉 django 模板 ;-))。我不知道 OP 是否愿意这样做。如果他这样做了,我想应该可以提供自己的“装载机”吗? (但我会把它留给你;-),或者至少是有更多经验的人)
【解决方案2】:

没有官方支持的方法可以通过 webapp 的 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 被使用是因为模板缓存使用模板的绝对路径作为键,所以任何真实文件都可以作为假模板源。但这是一个很可能会改变的实现细节。

【讨论】:

  • app.yaml 不是 App Engine 上的真实文件;它没有与应用程序一起上传。
  • 与 dev_appserver 一起使用!谢谢,上面已修复。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-04-23
  • 2016-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-11
相关资源
最近更新 更多