Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5 get view name

I'm struggling to get the view name in L5. Just as in WP, I'd like to add a specific page name (view name) for styling, like so:

<!-- View name: login.blade.php !-->
<div id="page" class="page-login">
    <h1>Inloggen</h1>
</div>

<!-- View name: register.blade.php !-->
<div id="page" class="page-register">
    <h1>Registreren</h1>
</div>

In L4 it can be done using composer to share the var across all views (How can I get the current view name inside a master layour in Laravel 4?). But I only need the view name once for my master layout.

Doing this:

<div id="page" class="page-{{ view()->getName() }}">

Gives me the following error Call to undefined method Illuminate\View\Factory::getName().

Thanks in advance!

like image 948
JasonK Avatar asked Apr 05 '15 15:04

JasonK


People also ask

What is @yield used for in Laravel?

In Laravel, @yield is principally used to define a section in a layout and is constantly used to get content from a child page unto a master page.

Where are views located in Laravel?

Views are stored in the resources/views directory.

How do I return a view in Laravel?

Views may also be returned using the View facade: use Illuminate\Support\Facades\View; return View::make('greeting', ['name' => 'James']); As you can see, the first argument passed to the view helper corresponds to the name of the view file in the resources/views directory.

What is view Laravel?

What are the views? Views contain the html code required by your application, and it is a method in Laravel that separates the controller logic and domain logic from the presentation logic. Views are located in the resources folder, and its path is resources/views.


1 Answers

Update your AppServiceProvider by adding a view composer to the boot method and using '*' to share it with all views:

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;    

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        view()->composer('*', function($view){
            $view_name = str_replace('.', '-', $view->getName());
            view()->share('view_name', $view_name);
        });

    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

{{$view_name}} will be made available to your blade templates.

like image 172
supernifty Avatar answered Oct 03 '22 19:10

supernifty