开发者

Using template.render() without a file reference

Is it possible to use template.render() without a file path?

I'd like to do dynamic string replacemnt for text properties in my datastore. Templating immediately came to mind. Perhaps there is another way? My thought was the following...

my_string = template.render(my_model.description,templat开发者_开发知识库e_dict)


Judging from the "google-app-engine" tag, I assume you are talking about the templating engine provided with google.appengine.ext.webapp? According to the documentation: "for your convenience, the webapp module includes Django's templating engine". So have a look at the Django docs for templates...

As far as I can tell, you should be able to do something like the following (I am assuming my_model.description contains your template string?):

t = template.Template(my_model.description)
my_string = t.render(template.Context(template_dict))

(It might also be useful to have a look at the webapp code for template.py)


There's no officially-supported way to do use a non-file-based template with webapp's template.render()

Here's an unsupported way that works with 1.5.1 (and may well not work thereafter):

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 is used because the template cache uses the absolute path of a template as a key, so any real file will do as a fake template source. But that's an implementation detail that may well change.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜