HTL conditional rendering while not affecting nested html

Viewed 269

Is it possible using HTL to not render a HTML element if a condition evaluates to false but still render the nested content? Example:

<A renderIf="${properties.value}">
   <B>my content</B>
</A>

If value is false then this would be rendered:

<B>my content</B>

If value is true this should be rendered:

<A>
   <B>my content</B>
</A>
2 Answers

This is exactly what data-sly-unwrap is for:

<A data-sly-unwrap="${!properties.value}">
   <B>my content</B>
</A>

(note the inverted condition wrt your example because when data-sly-unwrap evaluates to true, it will unwrap the element, i.e. only display the contents).

Condition based displaying in HTML is possible with something called templates. Basically what template does is to hide anything that is inside the tags, and display them when a condition turns out to be true. You need support of Javascript to achieve this.

Example:

function validate() {
  if (document.getElementById("userInput").value == "EXAMPLE ANSWER") {
    var temp = document.getElementsByTagName("template")[0]; // Give the correct index of template when you have more than 1 template tag
    var cloneNode = temp.content.cloneNode(true);
    document.body.appendChild(cloneNode);
  }
}
<input id="userInput" value="EXAMPLE ANSWER"/>
<button onclick="validate()">Validate</button>

<template>
  <h2>That's the right answer!</h2>
</template>

Related