使用模板.render()没有文件引用

2024-04-26 22:16:59 发布

您现在位置:Python中文网/ 问答频道 /正文

可以用吗模板.render()没有文件路径?在

我想对数据存储中的文本属性执行动态字符串替换。模板马上就浮现在我的脑海里。也许还有别的办法?我的想法是。。。在

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

Tags: 文件数据字符串路径模板stringmodelmy
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是因为模板缓存使用模板的绝对路径作为键,因此任何真正的文件都将作为伪模板源。但这是一个很可能会改变的实现细节。在

从“googleappengine”标签判断,我假设您所说的是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代码可能也很有用)

相关问题 更多 >