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!
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.
Based on @motto answer i was able to get the blade file in blink of an eye.
find()
is a function in the ViewFileFinder
class that search for views , paths and namespaces.
then explode the return to get the file name.
last()
is a helper function in laravel.
@php
$view1 = View::getFinder()->find('login');
$page_login= last(explode('/', $view)); // this return login.blade.php
$view2 = View::getFinder()->find('register');
$page_register= last(explode('/', $view)); // this return register.blade.php
@endphp
@if($page_login == 'login.blade.php')
<!-- View name: login.blade.php !-->
<div id="page" class="page-login">
<h1>Inloggen</h1>
</div>
@endif
@if($page_register == 'register.blade.php')
<!-- View name: register.blade.php !-->
<div id="page" class="page-register">
<h1>Registreren</h1>
</div>
@endif