如何在Adobe Sightly HTL中条件设置input元素的disabled属性
disabled Attribute in Adobe Sightly HTL Great question! When working with Adobe Sightly HTL, dynamically toggling boolean attributes like disabled on input elements is straightforward once you know the right syntax. Here are the cleanest, most idiomatic approaches:
1. Inline Conditional Attribute (Simplest & Recommended)
HTL has native support for boolean attributes. If you set the attribute’s value to an expression that evaluates to true, the attribute will be rendered without a value (which is valid HTML for boolean attributes like disabled). If the expression is false, the attribute won’t be included at all.
Example code:
<input type="text" disabled="${isInputDisabled}" />
- When
isInputDisabledistrue, this outputs:<input type="text" disabled> - When
isInputDisabledisfalse, this outputs:<input type="text">
This is the most concise and readable method for single boolean attributes.
2. Using the data-sly-attribute Directive
If you need more control (like handling multiple conditional attributes at once), use the data-sly-attribute directive.
Option A: Target the disabled attribute directly
You can conditionally assign the attribute by setting its value to an empty string (to include it) or null (to omit it):
<input type="text" data-sly-attribute.disabled="${isInputDisabled ? '' : null}" />
- When
isInputDisabledistrue, thedisabledattribute is added (empty value is valid HTML) - When
isInputDisabledisfalse, the attribute is excluded entirely.
Option B: Pass an attribute object
For scenarios where you might need to set multiple conditional attributes, you can pass an object that includes disabled only when your condition is met:
<input type="text" data-sly-attribute="${isInputDisabled ? {'disabled': ''} : {}}" />
When the condition is true, we pass an object containing the disabled attribute; when false, an empty object means no extra attributes are added.
A Note on Your Reference Syntax
The syntax you mentioned (<input ${condition ? disabled : ''} />) isn’t valid HTL. HTL requires that attribute values are wrapped in ${} within the attribute definition, not directly inserted into the element tag. The methods above follow proper HTL conventions and will work reliably in AEM.
内容的提问来源于stack exchange,提问作者volna

