Laravel 4 - understanding View::share()

跟風遠走 提交于 2019-12-05 04:03:25

View::share should be available anywhere within your application. A common place that it is used is in view composers, but it should be usable within a route or wherever you need it.

Yes, adding:

View::share('foo','bar');

in your routes.php file will make $foo (with a value of 'bar') available in all views. This is especially useful for something like Twitter Bootstrap's "active" navigation classes. For example, you could do:

View::share('navactive', '');

to make sure the navactive variable is set in all views (and thus won't throw errors) and then when you are making views (in your controller, for example), you could pass:

return View::make('one')->with('navactive', 'one');

and then in your view (preferably some bootstrappy blade template) you can do the following:

<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>

Basically if you want to share the variables through all view, you might first want to create a base route(E.x.:internalController.php) as a parent class then extend other controllers as a child of it(E.x:childController.php).

And yeah you will most likely set the view::share('foo', $bar) in the __constructor() of the internalController.php, since it lunches whenever the class is initialized, this way the parent class will serve the variable values to the child classes.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!