Dev Notes

Various Cheat Sheets and Resources by David Egan/Carawebs.

Add Body Class on Laravel Views


CSS, Laravel
David Egan

It is useful to add resource-specific classes to the body class of a page to allow elements to be targeted by CSS.

Pass Variable from Child View to Master Layout

Pass a relevant variable from the blade template:

{{-- /views/articles/index.blade.php --}}
...
@extends('layouts.master', ['body_class' => 'articles index'])
...

Then in /views/layouts/master.blade.php:

<body
  @unless(empty($body_class))
    class="{{$body_class}}"
  @endunless
  >

You need to check that the variable is not empty - otherwise, if $body_class isn’t passed in to the master template an error will occur.

Use @section

In the child blade template:

@section('pageClass', 'js-home-page')

In the master:

<body class="@yield('pageClass')">

References

https://www.reddit.com/r/laravel/comments/3i44nz/how_do_i_add_body_class_for_each_page/


comments powered by Disqus