how can i add a display filter in alpinejs like in vue?

After delving into the issues of Alpine.js Github repository, learnt that it is possible to call a function in x-text directive as Alpine.js can access any functions defined in the global scope as well as in the component scope.

For further details look at here and here

Declared the following function:

var date_format = function (value) {
    if (value) {
        return dayjs(value).format('YYYY-MM-DD hh:mm:ss');
    }
    else {
        return value;
    }
}

And referred it like this in x-text:

<div x-data="mdata()">
    <h3 x-text="name"></h3>
    <h3 x-text="date_format(created_on)"></h3>
</div>

<!DOCTYPE html>
<html>

<head>
    <title>Data time display in AlpineJS</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/alpinejs/2.3.0/alpine.js"
        integrity="sha512-nIwdJlD5/vHj23CbO2iHCXtsqzdTTx3e3uAmpTm4x2Y8xCIFyWu4cSIV8GaGe2UNVq86/1h9EgUZy7tn243qdA=="
        crossorigin="anonymous" defer></script>
    <script src="https://unpkg.com/[email protected]/dayjs.min.js"></script>
</head>

<body>
    <div x-data="mdata()">
        <h3 x-text="name"></h3>
        <h3 x-text="date_format(created_on)"></h3>
    </div>
    <script>
        const mdata = () => {
            return {
                name: "Carpet",
                created_on: Date.now(),
            };
        };
        var date_format = function (value) {
            if (value) {
                return dayjs(value).format('YYYY-MM-DD hh:mm:ss');
            }
            else {
                return value;
            }
        }
    </script>
</body>

</html>

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top