The Lightning Web Components Dev Guide gives this example in the article titled Render HTML Conditionally, where a conditionally-rendered div
element is wrapped in a template
element containing an if:true
attribute:
<!-- helloConditionalRendering.html -->
<template>
<lightning-card title="HelloConditionalRendering" icon-name="custom:custom14">
<div class="slds-m-around_medium">
<lightning-input type="checkbox" label="Show details" onchange={handleChange}></lightning-input>
<template if:true={areDetailsVisible}>
<div class="slds-m-vertical_medium">
These are the details!
</div>
</template>
</div>
</lightning-card>
</template>
In practice, you can add an if:true
or if:false
attribute to just about anything in LWC, and it will render or not render accordingly. Is there anything wrong with this alternative version, where the template
element is omitted and the if:true
attribute is applied directly to the div
? If not, why does Salesforce promote a pattern that is more verbose and leads to deeper nesting in HTML templates?
<!-- helloConditionalRendering.html -->
<template>
<lightning-card title="HelloConditionalRendering" icon-name="custom:custom14">
<div class="slds-m-around_medium">
<lightning-input type="checkbox" label="Show details" onchange={handleChange}></lightning-input>
<div if:true={areDetailsVisible} class="slds-m-vertical_medium">
These are the details!
</div>
</div>
</lightning-card>
</template>