How to use x-if and x-if “not” syntax in Alpine.js
I was recently working on a file where I wanted to use an if statement and an if not statement. Below is the Alpine.js syntax that worked for me.
Of importance, Alpine.js docs state that “x-if
must be declared on a <template>
tag.” My code snippet below is for a website’s contact form that uses the CMS Statamic.
It intends that only the success message is visible when the form is submitted successfully, and the form fields are hidden. Also, the form is visible when entering the page, and the success message is hidden.
<template x-if="success">
The content to show if the form had success
</template>
<template x-if="!success">
The content shows when the form loads.
The template for errors is included in this area.
This area is not shown when the success message (above) is shown.</template>
To note: the x-if=”!success” works because the exclamation mark or bang (!) is the “NOT” operator in Javascript. Using the ! in front of boolean returns the opposite value. Therefore x-if=”!success” reads as, “If not Success” show this template.
You can also use x-if conditionals, as shown on mywebtuts.com.
If this code snippet helped you, please let me know in the comments. You may also enjoy our other coding logic, javascript, and Statamic articles.