In one of the earlier post, I explained how to create a multifield component in sightly and using sling models. In this post, I’ll talk about how to create and use “sightly templates” in your component. Templating is a powerful feature introduced in Sightly, which helps in keeping your code clean and makes it more reusable. Identify the repetitive code blocks in your markup, create a template and reuse it wherever it is required.
Let’s see how to create a template and how to call it:
- A basic template can be created by below snippet. Each template requires an identifier. For Instance, in the below snippet I have created a template in a file “message.html” with the name “message1”.
<template data-sly-template.message1> <h2> This is template 1</h2> </template>
Now that the template is created, we can call using the data-sly-call and data-sly-use it as follows and use it in our code.
<div data-sly-use.messageRenderer="message.html"> <sly data-sly-call="${messageRenderer.message1}"/> </div>
- We have seen the example to create a basic template, now we’ll see how to pass parameters to our template.
<template data-sly-template.message2="${@ message}"> Message is <h2> ${message}</h2> </template>
To call this template in our code, we’ll have to use the below snippet.
<sly data-sly-test="${properties.text}" data-sly-call="${messageRenderer.message2 @ message=properties.text}"/>
The entire HTML will look like:
If there are multiple parameters, pass it as comma separated values.
<sly data-sly-call="${messageRenderer.message2 @ param1=param1,param2=param2 }"/>
Find the complete code in the Github repository.
Hope it helps !! 🙂