Alpine: Any recipe for bind data value to class?

Created on 29 Apr 2020  路  5Comments  路  Source: alpinejs/alpine

I have

x-data="{
  tags: [{
    ...
   color: 'red'
  }, {
    ...
   color: 'green'
  }]
}

Then i use x-for to loop tags, but how can i bind tag.color to <span>

<template x-for="tag in tags" :key="tag">
  <span class="tag-label" x-text="tag.label"></span> //  Current
  <span class="tag-label tag-{tag.color}" x-text="tag.label"></span> // Result, which i want to
</template>

Most helpful comment

<span :class="`tag-label tag-${tag.color}`" x-text="tag.label"></span>

Using :class (shorthand for x-bind:class) enables the use of expressions. The value of :class is a JavaScript string which is utilizing the backticks syntax for string interpolation.

All 5 comments

<span :class="`tag-label tag-${tag.color}`" x-text="tag.label"></span>

Using :class (shorthand for x-bind:class) enables the use of expressions. The value of :class is a JavaScript string which is utilizing the backticks syntax for string interpolation.

Oh, it's working now. Thank you so much.

I had similar issue where the class-name was not known before hand. This was for a multi-theme layout. I did something like this:

<body :class="`${palette} ${dark ? 'dark' : ''}`">

Just in case someone needs it.

I had similar issue where the class-name was not known before hand. This was for a multi-theme layout. I did something like this:

<body :class="`${palette} ${dark ? 'dark' : ''}`">

Just in case someone needs it.

In that case you could also do the following (using object binding for class):

<body :class="{ [palette]: true, dark: dark }">

In that case you could also do the following (using object binding for class):

<body :class="{ [palette]: true, dark: dark }">

This is much cleaner. Thanks!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

BernhardBaumrock picture BernhardBaumrock  路  3Comments

piotrpog picture piotrpog  路  3Comments

Calinou picture Calinou  路  4Comments

zaydek picture zaydek  路  3Comments

adinata-id picture adinata-id  路  4Comments