Laravel - Nested blade echos

2019-08-01 20:46发布

问题:

I am using a blade echo inside of a stylesheet reference in my header section. This is for specifying a CSS for a skin to the site.

The original line is:

<link href="{{ asset("/dist/css/skins/skin-default.min.css"}}" rel="stylesheet" type="text/css\" />

I am grabbing a skin setting per user and want to insert it into that line to change what the user wants as their skin. I have the setting pulled out into a variable from within a view service provider.

$view->with('visualSkin', Auth::user()->visualSkin);

This way I have $visualSkin set when all views are rendered.

How can I insert that into the asset href above and default it to a setting if the user has none set?

I can call the variable or set a default by doing:

{{ $visualSkin or "skin-default" }}

However, how can I inline that section with my asset href? Something like this does not work:

<link href="{{ asset("/dist/css/skins/{{ $visualSkin or "skin-red-trim" }}.min.css"}}" rel="stylesheet" type="text/css\" />

I've also tried some php trickery, but since it's blade formatting when inserting it into php echo, it doesn't get rendered by the blade process.

Can you nest blade echos?
Am I missing some character escaping?

回答1:

You don't need nesting! Inside blade tags, PHP is running, so you can concatenate strings naturally.

<link href="{{ asset("/dist/css/skins/" . $visualSkin or "skin-red-trim" . ".min.css")}}" rel="stylesheet" type="text/css\" />

Note that was missing the ) to close the asset( function.


Using {{ 'something' }} is the same that type: echo 'something'

So anything that you can do with an echo, you can do on the blade echo tags.