Laravel 4 - 了解View :: share()

use*_*178 9 laravel laravel-4

据我所知:

View::share('foo','bar');
Run Code Online (Sandbox Code Playgroud)

将在所有视图中提供$ foo.

但是,说View::share()只能在__construct()?中使用是否正确?

因为从外面__construct()我不能让它发挥作用.

Jas*_*wis 9

View::share应该可以在您的应用程序中随处使用 它使用的一个常见位置是视图作曲家,但它应该可以在路线中或任何需要的地方使用.

  • 只是为寻找一个好方法的人添加一些东西...把它放在你的基本控制器的```__construct()```方法中.;) (2认同)

Mat*_*lle 9

是的,添加:

View::share('foo','bar');
Run Code Online (Sandbox Code Playgroud)

在你的routes.php文件中,所有视图中都会提供$ foo(值为'bar').这对于Twitter Bootstrap的"活动"导航类特别有用.例如,您可以这样做:

View::share('navactive', '');
Run Code Online (Sandbox Code Playgroud)

确保在所有视图中设置导航变量(因此不会抛出错误),然后在制作视图时(例如在控制器中),您可以传递:

return View::make('one')->with('navactive', 'one');
Run Code Online (Sandbox Code Playgroud)

然后在您的视图中(最好是一些bootstrappy刀片模板),您可以执行以下操作:

<ul class="nav">
    @if ( Auth::user() )
    <li @if ($navactive === 'one') class="active" @endif><a href="{{{ URL::to('one/') }}}">One</a></li>
    <li @if ($navactive === 'three') class="active" @endif><a href="{{{ URL::to('three/') }}}">Three</a></li>
    <li @if ($navactive === 'five') class="active" @endif><a href="{{{ URL::to('five/') }}}">Five</a></li>
    @endif
</ul>
Run Code Online (Sandbox Code Playgroud)