Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable inside of asset declaration

I am trying to randomise a background using Laravel. I pass the $background variable to the view and then try to load it as an inline style.

However, I am struggling to declare the path to the asset and then call the variable together as it keeps erroring out.

My current code is :

<section class="page" style="background-image: url({{ asset('img/backgrounds/{{ $background }}.jpg') }});">

The $background is the variable and I am trying to reference the asset path.

Is there a better / easier way to do this? Or how can I get this to work. Don't mind using PHP code as an alternative if needs be.

Thanks

like image 238
StuBlackett Avatar asked Nov 17 '15 11:11

StuBlackett


1 Answers

You can't nest Blade tags, so you can't have {{.. {{...}} ..}}, but you don't need to, because the code inside a {{...}} is evaluated as if it were a <?php echo ... ?> snippet. So you can do one of two things:

Concatenate the variable into the string:

{{ asset('img/backgrounds/' . $background . '.jpg') }}

Or use double quotes " to evaluate the variable inside the string:

{{ asset("img/backgrounds/$background.jpg") }}
like image 90
Bogdan Avatar answered Jan 02 '23 14:01

Bogdan