Laravel 4 - understanding View::share()

耗尽温柔 提交于 2019-12-22 04:15:21

问题


From what I understand:

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

Will make $foo available in all views.

However, is it correct to say View::share() can be used only in the __construct()?

Because from outside __construct() I can't make it to work.


回答1:


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.




回答2:


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>



回答3:


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.



来源:https://stackoverflow.com/questions/16877948/laravel-4-understanding-viewshare

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