简体   繁体   中英

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,template_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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM