Home > Net >  Alpine3 js & Larvavel
Alpine3 js & Larvavel

Time:02-21

I'm having some issues trying to get the following code to work. I'm sure I'm over looking something simple but cannot spot it

My code is bringing up the error: Alpine Expression Error: unexpected token: string literal

<div 
    x-data="{ images: ['background-1.jpg', 'background-2.jpg'], index: 0}"
    x-init="index = Math.floor(Math.random() * images.length)">

    <div :style="'background-image: url(/img/'   $images[index]')'"></div>

CodePudding user response:

You are trying to use a mixed PHP-JS syntax. JS don't require the dollar sign prefix for variables (only if you added them originally).

The corrected syntax (with extra single quotation marks around the image URL):

<div :style="'background-image: url(\'/img/'   images[index]   '\')'"></div>

Or we can use the JS template literals as well with backtics (`) which is IMO more readable:

<div :style="`background-image: url('/img/${images[index]}')`"></div>
  • Related