Get Template
getTemplate
is used to load a Twig template via the API. One example use case is if you want to dynamically load a template when a modal is opened.
Usage
getTemplate
takes in the following object:
interface TemplateRequest {
template: string;
props: LooseObject;
}
template
is the path of your.html.twig
file in the theme folder. Exclude thetheme
path as well as the.html.twig
extension. For example, “theme/sections/item-modal.html.twig” would be passed in as “sections/item-modal”.props
is just an object that contains the props that your template requires in its schema (with each key representing a prop).interface LooseObject { [key: string]: any; }
Example
const templateRequest = {
template: 'sections/item-modal',
props: {
item: {
filters: {
id: item.id
}
}
}
};
try {
const template = await sdk.template.getTemplate(templateRequest);
} catch (error) {
// Handle errors
}
Return Value
On success a string of the rendered HTML template is returned.
An extremely simple example:
<div>Hello</div>
<div>Bye</div>
Error Handling
The rendering from the Template API follows the same logic as the production, meaning there are no debugging errors like in preview mode.
The error object thrown is in the form of:
interface TemplateError extends Error {
template: string;
}
The additional template
property provides the generic rendered HTML error template that would be rendered via the page on a failure. You can choose to use this to display a rendered error, or handle it how you see fit.