Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel yield attribute

I'm trying to set an attribute using @yield and @section, but how? I tried to use

<html @yield('mainApp')> 

and

@section('mainApp','id="myid"') 

but it returns id=&quot;myid&quot; instead of id="myid"

I know that I can manage it with a default id but I don't like this way, and also what if I need to use a custom attribute?

like image 988
Vixed Avatar asked Feb 12 '17 21:02

Vixed


People also ask

What is yield in Laravel?

In Laravel, @yield is principally used to define a section in a layout and is constantly used to get content from a child page unto a master page.

What is the difference between yield and section in Laravel?

@yield is a section which requires to be filled in by your view which extends the layout. You could pass it a default value through the second parameter if you'd like. Usages for @yield could be the main content on your page. @section is a section which can contain a default value which you can override or append to.

What is @section in Laravel?

@section directive is inject content layout from extended blade layout and display in child blade. The content of these section will be displayed in the layout using @yield directive. @parent directive will be replaced by the content of the layout when the view is rendered.

What is @include in Laravel?

@include is just like a basic PHP include, it includes a "partial" view into your view. @extends lets you "extend" a template, which defines its own sections etc. A template that you can extend will define its own sections using @yield , which you can then put your own stuff into in your view file.


2 Answers

Laravel escapes HTML by default. I therefore see that you have two choices.

  1. Expose the value to the view as a variable in your controller.

    view()->share('mainApp', sprintf('id="%s"', 'myid'));

Then output the value unescaped.

<html {!! $mainApp !!} 
  1. Only yield the id attribute value, not the entire attribute.

    @section('mainApp') myid @stop

    <html id="@yield('mainApp', '')">

like image 147
fubar Avatar answered Sep 22 '22 20:09

fubar


On your controller you do something like:

return view('my_page')->with('myid', 'myid'); 

and on your view/layout you do something like:

<html {{ $myid or '' }}> ... 

You don't need to yield for such a task.

like image 20
Waiyl Karim Avatar answered Sep 26 '22 20:09

Waiyl Karim