当前使用Laravel版本为5.2.43
涉及一个知识点 View::share()
, 官方文档(此链接是Laravel5.0版本,适用于5.2)。
直接上代码:
// 文件在app\Http\Controllers\Controller.php
namespace App\Http\Controllers;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesResources;
use Illuminate\Support\Facades\View;
class Controller extends BaseController
{
use AuthorizesRequests, AuthorizesResources, DispatchesJobs, ValidatesRequests;
public $module; // 模块
public function __construct()
{
View::share('active', [$this->module=> 'active']);
}
}
// 文件在app\Http\Controllers\ArticleController.php
namespace App\Http\Controllers;
use App\Http\Requests;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Auth, Gate;
use App\Article;
class ArticleController extends Controller
{
public $module = 'article'; // 标识当前模块为'article'
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct() {
parent::__construct();
}
}
前台模板:
<ul class="nav navbar-nav">
<li class="{{ isset($active['article']) ? $active['article'] : '' }}"><a href="{{ url('article') }}">文章</a></li>
</ul>