laravel 资产声明中的变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33755369/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Variable inside of asset declaration
提问by StuBlackett
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.
我正在尝试使用 Laravel 随机化背景。我将 $background 变量传递给视图,然后尝试将其作为内联样式加载。
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.
$background 是变量,我试图引用资产路径。
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.
有没有更好/更简单的方法来做到这一点?或者我怎样才能让它发挥作用。如果需要,不要介意使用 PHP 代码作为替代。
Thanks
谢谢
回答by Bogdan
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:
你不能嵌套 Blade 标签,所以你不能有{{.. {{...}} ..}}
,但你不需要,因为 a 中的代码{{...}}
被评估为好像它是一个<?php echo ... ?>
片段。因此,您可以执行以下两项操作之一:
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") }}