Greg
Greg

Reputation: 2609

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)

Upvotes: 2

Views: 441

Answers (2)

Dave W. Smith
Dave W. Smith

Reputation: 24966

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.

Upvotes: 0

Steven
Steven

Reputation: 28666

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)

Upvotes: 1

Related Questions