在视图中获取 Laravel 5 控制器名称 [英] Get Laravel 5 controller name in view

查看:34
本文介绍了在视图中获取 Laravel 5 控制器名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们的旧网站 CSS 设置为 body 标签具有控制器名称的 id 和操作名称的类,使用 Zend Framework 1.现在我们切换到 Laravel 5. 找到了通过Route类获取动作名称的方法,但是找不到控制器名称的方法.我在 Laravel 文档中没有看到任何类似的内容.有什么想法吗?

Our old website CSS was set up so that the body tag had an id of the controller name and a class of the action name, using Zend Framework 1. Now we're switching to Laravel 5. I found a way to get the action name through the Route class, but can't find a method for the controller name. I don't see anything in the Laravel docs like this. Any ideas?

这就是你如何处理行动.您注入 Route 类,然后调用:

This is how you do with action. You inject the Route class, and then call:

$route->getActionName().

我正在为控制器寻找类似的东西.我检查了整个路线类,没有发现任何东西.

I'm looking for something similar for controllers. I've checked the entire route class and found nothing.

推荐答案

如果您的布局是 Blade 模板,您可以创建一个视图合成器,将这些变量注入到您的布局中.在 app/Providers/AppServiceProvider.php 中添加如下内容:

If your layout is a Blade template, you could create a view composer that injects those variables into your layout. In app/Providers/AppServiceProvider.php add something like this:

public function boot()
{
    app('view')->composer('layouts.master', function ($view) {
        $action = app('request')->route()->getAction();

        $controller = class_basename($action['controller']);

        list($controller, $action) = explode('@', $controller);

        $view->with(compact('controller', 'action'));
    });
}

然后,您的布局模板中有两个可用变量:$controller$action.

You will then have two variables available in your layout template: $controller and $action.

这篇关于在视图中获取 Laravel 5 控制器名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆