2

I've tried a variety of ways, including the popular post here: Add View Name to CSS Class on Body

But it pulls up the master template, rather than the sub-template name. I use @yield and @extends and such. So at the moment this is what a part of my file system looks like in my views:

-Views
--Layouts
---=master.blade.php
--Shipments
---=index.blade.php

So my shipments.index file will @extends('layouts.master'), just so I don't have so much redundancy. However, referencing the above post, I get the following result:

<div id="page" class="layouts.master">

which is not what I'd like, I'd prefer at the very least "shipments.index", I don't mind if it's longer, I just want it identified.

4
  • Look into something like this. It's used to get the view directory, but with a bit of modification it could work for you
    – ljubadr
    Commented Oct 20, 2017 at 16:06
  • @ljubadr - what would I change in it? Using it outright just gives me a blank response in the html. No errors or anything, just nothing responding using the {{ $view_folder }} - do you have any suggestions? Thanks!
    – Matthew
    Commented Oct 20, 2017 at 22:08
  • I've created an answer, take a look and let me know if it works
    – ljubadr
    Commented Oct 20, 2017 at 22:20
  • Possible duplicate of Laravel 5 get view name
    – ljubadr
    Commented Oct 20, 2017 at 22:32

1 Answer 1

6

You can use Laravel View Composers

View composers are callbacks or class methods that are called when a view is rendered. If you have data that you want to be bound to a view each time that view is rendered, a view composer can help you organize that logic into a single location.

In the file app/Providers/AppServiceProvider.php, edit the public function boot() method

/**
 * Bootstrap any application services.
 *
 * @return void
 */
public function boot(Application $app)
{
    view()->composer('*', function($view) {
        view()->share('view_name', $view->getName());
    });
}

After this, in any blade template you will now have access to a variable

{{ $view_name }}

4
  • It looks like this is duplicate. Just saw other question
    – ljubadr
    Commented Oct 20, 2017 at 22:33
  • This version worked! Thank you so very much for the help!!
    – Matthew
    Commented Oct 21, 2017 at 3:15
  • One quick note: This will work for the view that you are loading, but it will not work for sub views, as it will always show main view name (when you do the @include('another.view'))
    – ljubadr
    Commented Oct 21, 2017 at 3:37
  • @Matthew I'm glad that I could help
    – ljubadr
    Commented Oct 21, 2017 at 3:38

Not the answer you're looking for? Browse other questions tagged or ask your own question.