AEM Sightly is a templating language that simplifies the integration of HTML and server-side logic. One of the key features of Sightly is the ability to use add inline-css to the component itself, so that your user experience requirements can be full-filed. In this article, we will explore how AEM Sightly enables developers to apply inline styles to elements dynamically, enhancing the flexibility and efficiency of web development.
1. Inline CSS with AEM Sightly
AEM Sightly allows developers to apply inline CSS to HTML elements using dynamic content. By leveraging the ${properties.maxHeight @ context=”styleString”}, developers can set the max-height property of an element based on the value of the maxHeight property defined in the AEM component dialog.
Consider the following example:
1 2 3 4 5 6 7 8 | <div id="${models.id}" class="cmp-container" style="max-height: ${properties.maxHeight @ context="styleString"}px"> <!-- Your content here --> </div> //output <div id="${models.id}" class="cmp-container" style="max-height: 300px"> </div> |
In this code snippet, the max-height property is set inline using the ${properties.maxHeight} value defined in the component’s dialog. The @ context=”styleString” ensures that the value is properly processed as a style string.
2. Benefits of Dynamic Inline CSS
Using ${properties.maxHeight @ context=”styleString”} for inline CSS with AEM Sightly offers several advantages:
- Flexibility: Inline CSS allows developers to adapt styles based on user inputs or system properties, making web pages more dynamic and responsive.
- Efficiency: By defining styles dynamically within the component code, developers can reduce the need for separate CSS rules and enhance the component’s reusability.
- Component-Level Customization: With dynamic inline CSS, component properties like maxHeight can be set individually for each instance of the component, granting greater customization.
2. Dynamic Styling with CSS via <style> tag
In addition to using inline styles, AEM Sightly also allows dynamic styling through CSS. By incorporating the ${models.id} and ${properties.maxHeight @ context=”styleString”} within a <style> block, developers can create more sophisticated and reusable styling rules.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <style> /* Style for the element with the given id (${models.id}) */ #${models.id} { max-height: ${properties.maxHeight @ context="styleString"}px; } </style> // output <style> #cmp-container1231432324234 { max-height: 300px; } </style> |
Utilizing the Sightly HTL 1.4 API, @context, will protect against cross-site scripting (XSS) vulnerabilities, HTL automatically recognises the context within which an output string is to be displayed within the final HTML output, and escapes that string appropriately. reference.