Last Updated: February 25, 2016
·
540
· darkliquid

Per-view IDs in Laravel

For my views, I like each page to have an identifier that tells me which view is being rendered. This allows me to easily share a bunch of generic styles but customise them on a per-view basis by using overrides triggered of these unique identifiers.

Simply, I create a View creator to set a variable, like so:

View::creator('*', function($view){
    if(!isset($view->page_identifier)) {
        $view->with('page_identifier', str_replace('.', '-', $view->getName()));
    }
});

This sets a variable $page_identifier that can be used in your layouts to set up a unique ID or class on your body tag (or whatever container you want).

For example, if you have a view in the directory app/views/products/show.blade.php then $page_identifier will be equal to products-show.

Now you can use this variable in your layouts to define an ID or class, e.g.

<body id="{{{ $page_identifer }}}">