x-if & <template> tag
x-if
x-if is used for toggling elements on the page, similarly to x-show, however it completely adds and removes the element it's applied to rather than just changing its CSS display property to "none".
Because of this difference in behavior, x-if should not be applied directly to the element, but instead to a <template> tag that encloses the element. This way, Alpine can keep a record of the element once it's removed from the page.
<template x-if="true">
<span x-text="message"></span>
</template>NOTE
If you don't like setting global CSS for x-cloak, you can use the above trick using x-if, to achieve the same behavior.
Unlike x-show, x-if, does NOT support transitioning toggles with x-transition (covered later).
<template> tag
The <template> tag in HTML is a mechanism used to define reusable, hidden chunks of HTML content that are not rendered in the DOM when the page loads. This content remains inactive until it is explicitly inserted or used via JavaScript.
NOTE
<template> tags can only contain one root level element.
The following code will not work, due to multiple root level elements inside <template> tag:
<template x-if="true">
<span>The next color is </span><span x-text="message">
</template>but this code will work:
<template x-if="true">
<p>
<span>The next color is </span><span x-text="message">
</p>
</template>Because <template> elements are "hidden" in browsers by default, you won't see the <span>, in the example above, until Alpine has had a chance to render the x-if="true" and show it.
