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>
You can also use x-if conditionals, as shown on mywebtuts.com.