Binding View::composer to match all views using wildcards?

我们两清 提交于 2019-12-05 23:14:55

问题


I have a navigation bar like this.

<li>Account</li>
   <ul>
      <li>Register</li>
      <li>Login/li>
      ...

I want to update this dynamically depending on Auth::check(). For example, if the user is logged in, "Account" will be changed with "My Profile Page" and child siblings will be replaced with an appropriate array.

I need to do this without editing View::make calls in my controllers. It looks pretty bad.

A solution like this is what I'm looking for;

View::composer('home.*', function($view) {
    if(Auth::check())
       return $view->nest('accountArea', 'home.navigation-loggedIn', null);
    else
       return $view->nest('accountArea', 'home.navigation-visitor', null);
});

If there are better alternatives, I would like to hear them too!


回答1:


Seems like the wildcards in Laravel works. They're just undocumented as of now.

View::composer('admin.layouts.*', function($view)
{
     if (Sentry::check()) $view->with('navigation', View::make('admin._partials.navigation'));
     else                 $view->with('navigation', null);
});

That's what I was looking for.

Update: Here is an alternative solution

You can also bind it to the layout, so all the subviews that extend that layout will benefit from composer.

View::composer('admin.layouts.main_layout', function($view)
{
     if (Sentry::check()) $view->with('navigation', View::make('admin._partials.navigation'));
     else                 $view->with('navigation', null);
});

It will bind composers to every view that does @extend('admin.layouts.main_layout').




回答2:


You can use View::share('variable', 'value') to share a variable across all views.




回答3:


Like Aristona says (thanks for de advice!): wildcards are allowed. Glancing at the code, we can see how Composers are Event Listeners, and in that section of the documentation is pointed out: Wildcard event listeners.

Adding a little bit more, ultimately, Str::is() is used by Events\Dispatcher to detect wildcar listeners. For example, something like this:

str_is('namespace::*.view', 'namespace::folder.view')

In short, I agree that would not hurt a small informative phrase :)



来源:https://stackoverflow.com/questions/16711854/binding-viewcomposer-to-match-all-views-using-wildcards

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