Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Render a template into a string?

Tags:

Is it possible to "render" a template into a string? I would like to use a template and fill that with some values that I then must save to the local disc.

The render method always send the template to the client. I want something similar to run a template but save the output from the template to a local string variable that I can store in the local file system.

like image 831
Henrik Avatar asked Jan 24 '12 07:01

Henrik


People also ask

What is render to string in Django?

render_to_string is a callable within the django. template. loader module of the Django project. get_template and select_template are a couple of other callables within the django. template.

What is render_ template_ string?

render_template_string is a Flask function from the flask. templating package. render_template is used to generate output from a string that is passed in rather than from a file in the templates folder. Note that render_template_string is sometimes imported from the flask package instead of from flask. templating .

What is rendering a template?

Rendering a template is indeed always about producing content, but for a slightly wider description of content. It could be a chunk of html, for example an ajax call to get new items might produce some html describing the new items, but it doesn't have to be.

What is template rendering in Django?

Rendering means interpolating the template with context data and returning the resulting string. The Django template language is Django's own template system. Until Django 1.8 it was the only built-in option available. It's a good template library even though it's fairly opinionated and sports a few idiosyncrasies.


2 Answers

It is simpler than you think:

def myTemplateString = g.render(template: "test", model: [foo: bar])
like image 169
Jan Wikholm Avatar answered Oct 01 '22 19:10

Jan Wikholm


If you are using Grails 2.x, you can use the PageRenderer class. Try something like this:

     grails.gsp.PageRenderer groovyPageRenderer

     void methodName() { 
         def contents = groovyPageRenderer.render(template:"yourTemplate", model:yourModel)
         //you can use contents as a string now
     }

This will work outside the scope of a web request as well, such as in a scheduled job or web service.

like image 26
Anuj Arora Avatar answered Oct 01 '22 17:10

Anuj Arora