Alpine.js < template > and x-if or x-if ! (not)

A

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. This is the Alpine.js syntax that worked for me.

To note, Alpine.js docs state that “x-if must be declared on a <template> tag.”  My code snippet below was used for a form on a website that uses Statamic as the CMS.

Its intent is that when the form is submitted successfully, only the success message is visible and the form fields are hidden. Also, on page entry, the form is visible and the success message is not visible.

<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.

About the author

Kelly Barkhurst

Designer to Fullstack is my place to geek out and to share tech solutions from my day-to-day as a designer, programmer, and business owner (portfolio). I also write on Arts and Bricks, a parenting blog and decal shop that embraces my family’s love of Art and LEGO bricks!

Add comment

By Kelly Barkhurst

Recent Posts

Archives

Categories