Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 4 Controller Templating / Blade - Correct method? [closed]

I've been reading through the Laravel 4 documentation and have been making a demo application to help with learning.

I couldn't find much documentation on the templating of views with blade and controllers. Which is the correct method or does it come down to personal preference?

E.g. 1

Controllers/HomeController.php

protected $layout = 'layouts.main';

public function showWelcome()
{
    $this->layout->title = "Page Title";
    $this->layout->content = View::make('welcome');
}

Views/layouts/main.blade.php

<html>
<head>
    <title>{{ $title }}</title>
</head>
<body>
    {{ $content }}
</body>
</html>

Views/welcome.blade.php

<p>Welcome.</p>

E.g. 2

Controllers/HomeController.php

protected $layout = 'layouts.main';

public function showWelcome()
{
    $this->layout->content = View::make('welcome');
}

Views/layouts/main.blade.php

<html>
<head>
    <title>@yield('title')</title>
</head>
<body>
    @yield('content')
</body>
</html>

Views/welcome.blade.php

@section('title', 'Welcome')
@section('content')
// content
@stop

What is the best convention and/or advantages of the the above?

like image 553
mylesthe.dev Avatar asked Jun 05 '13 22:06

mylesthe.dev


2 Answers

I don't store any layout information in the controller, I store it in the view via

@extends('layouts.master')

When I need to return a view in the controller I use:

return \View::make('examples.foo')->with('foo', $bar);

I prefer this approach as the view determines what layout to use and not the controller - which is subject to re-factoring.

like image 52
SamV Avatar answered Nov 09 '22 03:11

SamV


I don't like either of them. Layouts are probably the weirdest part of Laravel. The controller version doesn't really make sense; all methods of the controller then require that view. The @yield version is a mess of boilerplate. I made up this "method specific layouts":

public function index()
{
    return View::make('layouts.main', [
        'layout_data' => 'sup'
    ])->nest('content', 'welcome', [
        'view_data' => 'sup'
    ]);
}

I think it should be mentioned in the docs that this is an option.

like image 1
Farzher Avatar answered Nov 09 '22 02:11

Farzher