Custom Template for Component
All component templates are written using Handlebars templates. You can override these templates with your own. Keep in mind that you must provide valid Handlebars syntax. You can either define templates in-line or use a registerTemplate method.
Define Templates In-Line
// Use Handlebars syntax to create a template string
let customTemplate = `<div class="my-search">{{title}}</div>`
ANSWERS.addComponent('SearchBar', {
container: '.search-container',
template: customTemplate
})
Define Templates with registerTemplate
You can also define templates with the registerTemplate method. This method takes two arguments: a name and the template string.
To override an existing component's template, the name should match the default template. This is returned in the component's defaultTemplateName method, which you can find in the JS files for the various components. For example, here's the SearchBar.
ANSWERS.registerTemplate('search/search', `<div class="my-search">{{title}}</div>` );
ANSWERS.addComponent('SearchBar', {
container: '.search-container'
})
Which Should I Use?
registerTemplate is helpful because it can be called at any point (whereas addComponent can only be called once), allowing for dynamic templates. However, in most cases, defining the template inline will suffice. registerTemplate is most helpful for creating custom components.
Using a Custom Renderer
If you want to use your own template language (e.g. Soy, Mustache, Groovy, etc.), you should NOT use the template argument. Instead, you can provide a custom render function to the component.
ANSWERS.addComponent('SearchBar', {
container: '.search-container',
render: function(data) {
// Using native ES6 templates -- but you can replace this with Soy,
// or any other templating language as long as it returns a string.
return `<div class="my-search">${data.title}</div>`
}
})