Execute a Template
Steps
This page executes a template from a Java component, with org.xwiki.template.TemplateManager. Templates explains how the name you pass is resolved.
- Inject the component:
@Inject private TemplateManager templateManager; - Look the template up, when you need to know whether it exists before using it:
Template template = this.templateManager.getTemplate("mytemplate.vm");The result is null when no source answers the name. Template gives access to the id and the path of the template, and to its content as a TemplateContent.
- Render the template, which executes it and returns the result in the output syntax:
String html = this.templateManager.render("mytemplate.vm"); - Produce blocks instead, when the result is to be inserted in a page that is being rendered:
XDOM result = this.templateManager.execute("mytemplate.vm"); Block inline = this.templateManager.execute("mytemplate.vm", true); XDOM parsed = this.templateManager.getXDOM("mytemplate.vm");execute runs the template, and its second form produces blocks fit for an inline context such as the inside of a paragraph. getXDOM parses the template without executing it.
- Check what the call returned, here for a template producing an information box:
<div class="box infomessage">Some info message</div>
FAQ
What is the difference between render and renderNoException?
Both execute the template. render throws the failure, while renderNoException catches it and returns the error as part of the result, which is what a template rendering the user interface needs.
Which skin does the template come from?
The current one. renderFromSkin executes the template from a skin you name instead, without falling back on the skin of the request.