AEM different ways to use HTL sly

1.6k Views Asked by At

What is the difference between to use:

<div data-sly-resource="${'foo' @ resourceType="var"} ... ></div>
or
<sly data-sly-resource="${'foo' @ resourceType="var"} ... ></sly>
or
<sly data-sly-resource="${'foo' @ resourceType="var"} ... />

And when I should use data-sly-unwrap?

1

There are 1 best solutions below

0
On

I think the best way to understand when to use what, is to understand the fundamentals of HTL.

Most of HTL can be written around existing HTML tags and attributes, such as

<div data-sly-resource="${'foo' @ resourceType='var'}" ... ></div>

However, in instances where you don't want the HTML element to be present in the output, you can leverage the sly element. When an sly element is used it is removed from the final rendered HTML automatically.

For e.g., <sly data-sly-resource="${'foo' @ resourceType='var'}" ... ></sly> or <sly data-sly-resource="${'foo' @ resourceType='var'}" ... /> both output the same HTML which is directly including the output of the resource foo without adding any extra tags.

But if the same was written using an HTML element such as the following

<div data-sly-resource="${'foo' @ resourceType=""var}" ... ></div>

the generated HTML will contain a parent div tag around the included resource's output as shown below <div>HTML output of foo goes here</div>

The data-sly-unwrap comes into play in such scenarios. Adding the data-sly-unwrap to an HTML element will exclude that element from the generated output, but would output all the child HTML.

For e.g., <div data-sly-resource="${'foo' @ resourceType='var'}" ... data-sly-unwrap></div> and <sly data-sly-resource="${'foo' @ resourceType='var'}"></sly> and <sly data-sly-resource="${'foo' @ resourceType='var'}" /> would produce the same output.

Please note that the data-sly-unwrap on a sly element has no effect as the sly is removed by the processor anyways.

However, I think the power of data-sly-unwrap lies when using it with conditional statements. For e.g., if a parent element needs to present only in certain scenarios, then using it in the following way is much cleaner than writing multiple if conditions as we used to do in JSPs or JSTLs.

<div class="parent" data-sly-unwrap="${hideParent}">
    <img class="img" src="../../xyz.jpg" />
</div>

More on data-sly-unwrap here.