Laravel定义了很多常用的全域变数,但如果我们想要自己定义的话,就必须靠这个来执行了,譬如每页都会有专有的<h1>标题,若要每页都写的话,未免太麻烦!不如开一个观点来专门显示就好,所以需要定义一个函数来判断目前页面的别名,然后自动取得对应的标题名称即可。
/* * Application Service Providers... */ App\Providers\AppServiceProvider::class, App\Providers\EventServiceProvider::class, App\Providers\RouteServiceProvider::class,
App\Providers\HelperServiceProvider::class,
新增app / Providers / HelperServiceProvider.php
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class HelperServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
}
/**
* Register the application services.
*
* @return void
*/
public function register()
{
foreach (glob(app_path().'/Helpers/*.php') as $filename)
{
require_once($filename);
}
}
}
新增app / Helpers / AdminHelper.php
if ( ! function_exists('breadcrumbs'))
{
/**
* Return breadcrumbs for each resource methods
*
* @return string
*/
function breadcrumbs()
{
$route = Route::currentRouteName();
// get after last dot
$index = substr($route, 0, strrpos($route, '.') + 1) . 'index';
$breadcrumbs = '<div class="page-bar">';
$breadcrumbs .= '<ul class="page-breadcrumb">';
$breadcrumbs .= '<li><i class="fa fa-home"></i> <a href="'.route('admin.root').'"> '.trans('admin.menu.home').'</a></li>';
// if not admin root
if(strpos($route, 'root') === false)
{
$breadcrumbs .= strpos($route, 'index') !== false ? '<li class="active">' : '<li>';
$parent_text = strpos($route, 'index') !== false ? trans($route) : trans($index);
$breadcrumbs .= strpos($route, 'index') !== false ? $parent_text : '<i class="fa fa-angle-right"></i> <a href="'.route($index).'">'.$parent_text.'</a>';
$breadcrumbs .= '</li>';
if(strpos($route, 'index') === false)
{
$breadcrumbs .= '<li class="active"><i class="fa fa-angle-right"></i>'.trans($route).'</li>';
}
}
$breadcrumbs .= '</ul></div>';
return $breadcrumbs;
}
}
if ( ! function_exists('header_title'))
{
/**
* Return the header title for each page
*
* @return string
*/
function header_title()
{
$route = Route::currentRouteName();
$title = '<h1 class="page-title">';
$title .= trans(Route::getCurrentRoute()->getName());
if( strpos($route, 'index') !== false )
{
$new = substr($route, 0, strrpos($route, '.') + 1) . 'create';
if(Route::has($new))
{
$title .= '<small>';
$title .= '<a href="'.route($new).'" title="'.trans($new).'">';
$title .= '<i class="fa fa-plus"></i>';
$title .= '</a>';
$title .= '</small>';
}
}
$title .= '</h1>';
return $title;
}
}
在适当的viess插入:(ex:header.blade.php)
{!! header_title() !!}
{!! breadcrumbs() !!}
就可以看到目前页面的名称(通过路由别名):header_title(),以及页面层级breadcrumbs()
来自 http://laravel51.blogspot.jp/2015/08/2-helpers-function.html