0

I want to offload some HTML sections of my site into partials (includes) files rather than repeating the information in each view or layout. However, I also need them to contain specific data. An obvious example is the head section; I would like to put this into a partial, however I also want to be able to set the document title and META fields for each page.

I think the best way is to use Laravel's view-composer

As per the docs, I can use an array to define the composer for multiple views at once:

View::composer(array('view1','view2', 'view3'), function($view)
{
    $view->with('count', User::count());
});

However, what if I want to use this composer for every view, as I do in this case?

There's a few answers kicking around SO (such as this one) which suggests I use a wildcard. So here's my code:

View::composer('*', function($view)
{
    $view->with('header', View::make('partials.head', $view->getData()));
    $view->with('footer', View::make('partials.footer', $view->getData()));
});

Here's the problem: Using this is currently giving me an out of memory error, which suggests that it is very inefficient (and therefore that I really shouldn't be doing this).

So do I really need to pass an array listing every page on my website?

Isn't there a way to use composer for every page rendered, like I can with View::share(); ?

Community
  • 1
  • 1
Inigo
  • 8,110
  • 18
  • 62
  • 110

2 Answers2

2

If the data is going to be unique for each view, there's no point in putting it in a view composer; you can do this just by using blade templates, and pass the page-specific data to the view from your controller.

Set up header and footer partials, then set up a base template that uses @include to load your header and footer partials, then a section for your content with @yield('content').

<!DOCTYPE html>
...
@include('partials.header')

@yield('content')

@include('partials.footer')
...

Then your individual page's views would each extend this base template:

@extends('base')

@section('content')
//...specific page content here
@stop

In your header and footer partials, include {{ $someData }} for whatever specific needs to change from page to page, and pass that data to each view from the controller.

damiani
  • 7,071
  • 2
  • 23
  • 24
  • Thanks! A case of barking up the wrong tree I think... I just assumed that variables wouldn't be available in the child partials, and for some ridiculous reason I didn't even think to try it. Problem solved, cheers! – Inigo Oct 20 '14 at 20:24
0

This is now possible in Laravel 5.5

Put this is your AppServiceProvider boot method:

View::share('data', [1, 2, 3]);
Adam
  • 25,960
  • 22
  • 158
  • 247