I am using Laravel 4 and blade templates, and running into an issue when I try and extend a template.
In my layout I have
#yield('content')
and in my page I have
#section('content')
Welcome {{ $name }}
#stop
which works fine, I've created another page very similar to my first, and just want to change override the admin content section. The other sections in the template are fine.
so I extend my page, and do
#section('content')
Hello!
#stop
I get an undefined notice with the $name variable.
I tried
#section('content')
Hello!
#overwrite
and same deal, I get the notice error.
I checked my controller and it IS using the correct template. I am not calling #parent so I don't understand, how can I overwrite a section in a template with out notice errors?
Blade layouts work their way up the tree to the route or master view before rendering any of the children. Thus, nested views that extend others must always have their parent rendered before they are. As a result, parent views that contain sections will always be rendered prior to the child.
To overcome the problem you are experiencing it is a good idea to only ever nest pages that don't overwrite parents sections that contain variables, as the parents content will always be rendered before the child.
As the above ideal can't always be adhered to or a parents section content is still required, a good alternative method would be to use view composers. View composers give you an opportunity to declare variables for any specific view whenever they are rendered.
View::composer(array('pages.admin'), function($view)
{
$view->with('name', Auth::user()->username);
});
Another alternative would be to use a view creator. Creators are fired the moment a view is instantiated rather than rendered. This method allows you to overwrite the variable should you so wish prior to the view being rendered.
View::creator(array('pages.admin'), function($view)
{
$view->with('name', Auth::user()->username);
});
You can read up more about these methods in the documentation here. (Or here for the Laravel 5 documentation.)
I can't guarantee support for Laravel 4 but for those looking for a solution that works in Laravel 5.5 (and probably a fair bit further back – hard to check) is to define the variables you need when #extending.
E.g. in the example in the question:
#extend('my.parent.view', ['name' => ''])
This approach can be especially useful if the data needed is available to the child-view, but under a different name.
E.g. if a parent-view needed a $parent variable, but the child view only has a $child variable which has a property referencing the parent, you might do:
#extend('my.parent.view', ['parent' => $child->parent])
I am not sure if this is a bug or intentional, but it seems like Laravel renders the variables before interpreting blade instructions.
The workaround would be this:
views/layouts/testlayout.blade.php:
<html>
<body>
#yield('sidebar', 'This is the master sidebar. {{ $name }}' )
<div class="container">
#yield('content')
</div>
</body>
</html>
actual view: views/test.blade.php
#extends('layouts.testlayout')
#section('sidebar')
No variable in the child
#stop
#section('content')
This is a child content
#stop
This prevents the variable $name to get rendered if there is a section with that name in the actual view. It seems like this is the approach if the content in the layout file contains a variable
In your page try this :
#section('content')
#hasSection('content')
#yield('content')
#else
Welcome {{ $name }}
#endif
#stop
And read this post for more inspiration https://laracasts.com/discuss/channels/laravel/laravel-blade-layouts-inheritence-problem
I found an easy solution for this problem :)
Just add the # symbol before the variable/method you call in the parent view. If there is an error (notice/warning) PHP will ignore that and continue the execution.
It's not perfect, but save us to code view/composers.
Hope this help!
Related
Laravel 5.4 Blade introduced the concept of components & slots - but I can't see what they add over the traditional #include. As I understand, with component/slots, you do:
In template component-tpl.blade.php:
<div class='container'>
<h1>{{$slot1}}</h1>
<h2>{{$slot2}}</h2>
</div>
Using slots in page template, you do:
#component('component-tpl')
#slot('slot1')
The content of Slot 1
#endslot
#slot('slot2')
The content of Slot 2
#endslot
#endcomponent
What functionality does that provide over the older:
#include('component-tpl',['slot1'=>'The content of Slot 1',
'slot2'=>"The content of Slot 2"])
using the exact same 'component-tpl.blade.php' Blade template?
What am I missing? Thanks for any insights.
Chris
As stated, there's no functional difference I was incorrect - see benjaminhull's answer for details on variable scoping and passing blade syntax code. The following still holds for basic usage, though.
If a slot could contain HTML, then using a component will give a cleaner syntax in your blade files.
#component('test')
<strong>This text has html</strong>
#endcomponent
versus
#include('test', ['slot' => '<strong>This text has HTML</strong>'])
Equally, if a component has no slots, then an include may be preferred:
#include('test')
versus
#component('test')
#endcomponent
There are two key differences.
1. Variable scope
As described in #DavidHyogo's answer, a component only sees variables explicitly passed to it. So you have to give it all variables like so...
#component('my-component', ['foo' => 'bar', 'etc' => 'etc'])
Whereas an include will adopt all variables from the global/current scope by default - unless you define an explicit set of variables to pass it, which then becomes local scope again.
{{-- This include will see all variables from the global/current scope --}}
#include('my-component')
{{-- This include will only see the variables explicitly passed in --}}
#include('my-component', ['foo' => 'bar', 'etc' => 'etc'])
2. Component's {{ $slot }} vs include's {{ $var }}
When using a {{ $slot }} in a component, you can give it blade syntax code e.g...
{{-- alert.blade.php --}}
<div class="alert">{{ $slot }}</div>
#component('alert')
<div>Hello {{ $name }} #include('welcome-message')</div>
#endcomponent
Note how the slot will receive html AND blade syntax code and just deal with it.
This is not possible with includes because you can only pass variables into includes...
{{-- alert.blade.php --}}
<div class="alert">{{ $slot }}</div>
#include('alert', ['slot' => "I CAN'T PASS IN BLADE SYNTAX HERE!"])
It could be done in a more hacky way by grabbing a fresh view() helper and passing it some variables to compile the output we want to pass into the slot, but this is what components are for.
I think I've tracked down another crucial difference. For instance, from the documentation for 5.4:
Blade's #include directive allows you to include a Blade view from within another view. All variables that are available to the parent view will be made available to the included view:
As far as I can tell, components have a different scope from a containing view and so the variables available to the parent view are not available within the component. You need to pass a variable to a component like this:
#component('alert', ['foo' => 'bar'])
#endcomponent
This discussion is related to this problem:
Use variables inside the Markdown Mailables
As the documentation says:
Components and slots provide similar benefits to sections and
layouts; however, some may find the mental model of components and
slots easier to understand.
For me most important thing is component needs a class. So when I need just a simplest reusable part of html (blade) there is no need to create blade file + php file, just simple #include with subview is enough ;)
When I include a blade template that extends a base blade, any variables within the section of the included blade show only the variables of the first iteration.
Reading around it seems the render order here is important, and views are rendered before variables, or vice versa.
Note
I have read this SO question/answer: Laravel Blade #yield variable scope
The below snippet is greatly reduced in complexity, so the example could be restructured to exclude sections/extends. However my real case can't be
Example
// index.blade.php
//
#foreach($jobs as $job)
{{ $job->id }} // <-- Correct output, 1,2,3,..N
#include('job-detail', ['id' => $job->id])
#endforeach
Then in the job detail blade
// job-detail.blade.php
//
#extends('job-base')
A: {{ $id }} // <-- Correct output, 1,2,3,..N
#section('content')
B: {{ $id }} // <-- Incorrect output, 1,1,1,..1 (or whatever the first index is)
#endsection // have also tried #stop
Then in the job base blade
// job-base.blade.php
//
#yield('content') // Have also tried #section('content') + #show
After wading through the source code, namely BladeCompiler and View/Factory I noticed the following snippet:
protected function compileOverwrite($expression)
{
return '<?php $__env->stopSection(true); ?>';
}
In the background Laravel appears to store rendered content (by including the file, and extract current variables in a ob_style fashion) in a keyed array, with the view name being the key.
When stopSection is not passed a boolean true, it creates a new key, and the view gets the data from the original key.
Long story short, it's now undocumented (for 5.1+) but can be found in the docs for 5.0:
https://laravel.com/docs/5.0/templates
However it doesn't really explain the "why". This page seems to explain it a little better:
http://laravel-recipes.com/recipes/244/stopping-injecting-content-into-a-section-and-overwriting
I need to pass a variable to an included Blade file. I have attempted this two-ways; however, neither have been successful.
Pass a variable, title, to the included file:
#section('left')
#include('modal', ['title' => 'Hello'])
#stop
Use #yield and set the section:
#section('left')
#include('modal')
#section('title')
Hello
#stop
#stop
I am using Laravel 4.2. I am unaware if what I am trying to do is possible, but I imagine it is.
According to the documentation, the include-way should be the way to do it:
Including Sub-Views
#include('view.name')
You may also pass an array of data to the included view:
#include('view.name', array('some'=>'data'))
My hunch is that $title is conflicting with another variable in your nested templates. Just for troubleshooting, try temporarily calling it something else.
pass an array of data to the included view
#include('view.name', array('some'=>'data'))
then use this on view/name folder
{{ $some }}
I am trying to implement themes in a site so that certain pages have a different look and feel (and features) than other pages.
I have master.blade.php which contains the full HTML structure and has #section and #yield to get the content:
<html>
<body>
#section('master-template')
<?php
view()->share('masterTemplate', 'general');
$masterTemplate = "general";
?>
#stop
<header>
#section('nav-1')
#include('layout.navs.house-links')
#show
#section('nav-2')
#include ('layout.navs.contact-links')
#show
#section('nav-3')
#include('layout.navs.product-links')
#show
#section('nav-4')
#show
</header>
#yield('content')
</body>
</html>
I then have ford.blade.php which extends master, and overwrites some things:
#extends('templates.master')
#section('master-template')
<?php
view()->share('masterTemplate', 'ford');
$masterTemplate = "ford";
?>
#overwrite
#section('nav-1')
#include('layout.navs.house-links')
#overwrite
#section('nav-2')
#include ('layout.navs.contact-links')
#overwrite
#section('nav-3')
#include('layout.navs.product-links')
#overwrite
Then a regular page on the website will extend master.blade, and anything that requires the Ford navigation bar and colour scheme will extend the ford.blade template.
I then bound a view composer to layout.navs.product-links which gets the $masterTemplate variable from the view data and checks if it is one of our themes (like "ford"). If it is a regular page, it will bind vehicle ranges for all manufacturers to the view, and if it is a ford page, it will only bind the ford ranges to the page. The pseudo-code of the view composer is below:
public function compose(View $view)
{
// Get the view data
$viewData = $view->getData();
// Check for $masterTemplate view variable
if (isset($viewData['masterTemplate'])) {
$template = $viewData['masterTemplate'];
if ($template == "ford") {
$ranges = $this->getRangesForManufacturer($template);
}else {
$ranges = $this->getRangesForAllManufacturers();
}
$view->with('ranges', $ranges);
}
}
The problem is, because ford.blade extends master.blade, BOTH views get rendered behind the scenes. So the above view composer logic is useless because it runs twice on the "ford" page, once for master.blade and then again for ford.blade.
I proved this by checking the queries that are running using Laravel DebugBar.
How can I bind a variable $masterTemplate for use in all views (and partials) to check logic inside a view whether it is a "ford" or "general" page? I did it with #section and #overwrite in ford.blade but this seems to not work everywhere.
How can I use a view composer to bind data to a partial view that is #included by ford.blade and master.blade, because ford.blade extends master.blade and so the view composer gets executed twice.
At first glance, #overwrite might do what you told it to (except for #stop being enough, see how to extend a layout).
As a workaround: How about a redesign where you have a meta-master-template which contains the general stuff and is extended by both the ford and the master (i.e. general) template, depending on which part you need? (You could then rename master to general and meta-master to master)
That would skip your problem, because only one would be defined in each instance.
I was wondering if it is possible to nest templates inside of templates in Laravel 4. I would like to have a master wrapper template that would include things like the doctype, header and footer and then be able to load in templates into the master templates body section.
This would give me the flexibility of having a nested template for my application pages without having to duplicate code while giving me the ability to use the master template for non-application pages.
Can someone please provide an example as to how this would be done using blades templating engine? Is it possible to pass in a value from the router and then have that value be pushed down to your nested template?
EDIT:
Here is my code for index.blade.php
#extends('layouts.master')
#section('title')
Some page
#endsection
#section('content')
#include('layouts.app')
#endsection
You can try this for multiple level nesting
//index.blade.php
#extends('layouts.master')
#section('title')
#parent
:: new title
#stop
#section('content')
<p>some static contents here</p>
#stop
//app.blade.php
#section('content')
#parent
<p>Add here what ever you want to add</p>
#stop
now either from your Route or Controller you can nest the index and app, ex-
return View::make('index')->nest('content','layouts.app');
And in case you want to pass data to child view you can do this by passing the data as third parameter to nest()
return View::make('index')->nest('content','layouts.app',$data);