Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel blade template specific code

Currently we are using the Laravel framework on several projects, but one issue we keep running into which i don't like is the following issue:

Lets say you have a Homepage and a Content page

HomepageController has all Homepage specific php code ContentpageController has all Content specific php code

we have an app.blade.php that does

@yield('page')

HomepageController calls the view homepage.blade.php containing

@extends('app')

@section('page')
     Some HTML part
     @include('parts.top_5')
@endsection

ContentController calls the view content.blade.php containing

@extends('app')

@section('page')
     Some different HTML part
     @include('parts.top_5')
@endsection

Here you can see both pages include parts.top_5, the top 5 needs some specific variables to output the top5. Now the issue is we are currently copying the code for the top5 variables in both controllers or in grouped middleware but is there a better solution to generate some blade specific variables when the part is included? So a bit like running a controller function on loading the blade template?

I have been searching the internet but can't seem to find anyone with the same question. Hopefully someone can help me on this mindbreaking issue!

like image 953
RemcoDN Avatar asked May 22 '15 11:05

RemcoDN


People also ask

Can we write PHP code in blade template Laravel?

Unlike some PHP templating engines, Blade does not restrict you from using plain PHP code in your templates.

Can I use blade template without Laravel?

You could download the class and start using it, or you could install via composer. It's 100% compatible without the Laravel's own features (extensions).

What is the advantage of Laravel blade template?

The blade templates are stored in the /resources/view directory. The main advantage of using the blade template is that we can create the master template, which can be extended by other files.

What is yield (' content ') 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.


1 Answers

You can add this binding to AppServiceProvider

(or any custom ServiceProvider You want)

like this:

public function boot()
{
    $view->composer('parts.top_5', function($view) {
        $view->with('any_data' => 'You want');
    })
}

This way any time Laravel will compose parts.top_5 view this closure method will be triggerd.

And in documentations it's here: http://laravel.com/docs/5.0/views#view-composers

like image 52
D. Cichowski Avatar answered Oct 05 '22 07:10

D. Cichowski