Different background images when using the same Laravel Layout

css, html, laravel, laravel-4, laravel-blade

Solution

Instead of styling the `body` like this:

body{
    background-image: url('/images/image.png');
    background-size: cover;
}

Apply style to your `view`'s parent element, something like this:

.view_parent_image1{
    background-image: url('/images/image1.png');
    background-size: cover;
}

.view_parent_image2{
    background-image: url('/images/image2.png');
    background-size: cover;
}

Then use it like this:

// View 1
@extends('layouts.master')

@section('content')
    <div class='view_parent_image1'>

    </div>
@stop

In another view use the class `view_parent_image2` instead and so on:

    // View 2
@extends('layouts.master')

@section('content')
    <div class='view_parent_image2'>

    </div>
@stop

Update: Another way to do this:

// In your master layout
<body class='{{ $bodyClass or "default" }}'>

When loading view:

return View::make('viewname')->with('bodyClass', 'imageOne');

CSS:

.default { ... }
.imageOne { ... }

You can also share a global variable from the `BaseController`:

View::share('bodyClass', 'imageOne');

Finally (maybe best) you can create view composers to automatically set the `class` for a view:

View::composers(array(
    'ViewComposers@homeViewComposer' => 'home.index',
    'ViewComposers@aboutViewComposer' => 'about.index',
));

class ViewComposers {
    public function homeViewComposer($view)
    {
        return $view->with('bodyClass', 'homeViewClass');
    }

    public function aboutViewComposer($view)
    {
        return $view->with('bodyClass', 'aboutViewClass');
    }
}

CSS

.homeViewClass { ... }
.aboutViewClass{ ... }

If you need details about how to create and where to place `view composers` then you may follow this answer.

Problem

I have one layout for my laravel application. I have four views that extend this layout. However, I want a different background image for every view. My Layout.blade.php file looks like this: ``` <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>TITLE</title> <link rel="stylesheet" href="{{ asset('css/bootstrap.min.css') }}" /> <link rel="stylesheet" href="{{ asset('css/style.css') }}" /> </head> <nav> <!-- NAV STUFF HERE --> </nav> <body> <div class="container"> @yield('content') </div> </body> </html> ``` I styled my body in the style.css file like so: ``` body{ background-image: url('/images/image.png'); background-size: cover; } ``` This styling technique self-evidently gives each view the same background image, which I don't want. I want to be able to set a different background image for each view. So how do I set each page to have a different background image but still keeping the functionality of them extending a common layout? Thanks.

Original source