如何在laravel中设置视图文件路径? [英] How to set view file path in laravel?

查看:1055
本文介绍了如何在laravel中设置视图文件路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用于laravel应用的目录结构,如下所示:

I have a directory structure for laravel app like this:

app/
   admin/
      controllers/
      views/ -> for admin views
   ...
   views/ -> for frontend views

如何在admin中设置控制器的视图路径?我不想使用View::addLocationView::addNamespace,因为我可能为admin和前端使用相同的视图文件名,并且不想为每个View::make('namespace::view.file')添加名称空间.

How can I set the view path for controllers in admin? I don't want to use View::addLocation or View::addNamespace because I might have the same view file name for admin and frontend, and don't want to add a namespace for every View::make('namespace::view.file').

我在 http://laravel.com/api/4.2/Illuminate中看到/View/View.html 中有一个setPath方法,但是我怎么称呼它呢? View::setPath引发了未定义的方法错误.

I see in http://laravel.com/api/4.2/Illuminate/View/View.html there is a setPath method, but how do I call it? View::setPath raised undefined method error.

推荐答案

您有两种方法可以实现目标.首先,让我们看一下app/config/view.php.这就是定义视图加载路径的地方.

You have two ways to accomplish your goal. First, let's have a look at app/config/view.php. That's where the path(s) for view loading are defined.

这是默认设置:

'paths' => array(__DIR__.'/../views'),

方法1:加载两个目录

您可以轻松地将管理目录添加到阵列中

Method 1: Load both directories

You can easily add the admin directory to the array

'paths' => array(
    __DIR__.'/../views',
    __DIR__.'/../admin/views
),

现在这有一个很大的缺点:视图名称必须是唯一的.否则,将采用首先指定的路径中的视图.
由于您不想使用视图命名空间,因此我想您也不需要类似admin.viewname的语法.您可能还会更喜欢方法2;)

Now the big disadvantage of this: view names have to be unique. Otherwise the view in the path specified first will be taken.
Since you don't want to use a view namespace I suppose you don't want a syntax like admin.viewname either. You'll probably like method 2 more ;)

可以使用Config::set方法在运行时更改每个Laravel配置.

Every Laravel config can be changed at runtime using the Config::set method.

Config::set('view.paths', array(__DIR__.'/../admin/views'));

显然,对配置进行设置不会更改任何内容,因为它会在应用程序引导时加载并随后被忽略.

Apparently setting the config won't change anything because it is loaded when the application bootstraps and ignored afterwards.

要在运行时更改路径,必须创建FileViewFinder的新实例.
看起来像这样:

To change the path at runtime you have to create a new instance of the FileViewFinder.
Here's how that looks like:

$finder = new \Illuminate\View\FileViewFinder(app()['files'], array(app_path().'/admin/views'));
View::setFinder($finder);

方法3:使用addLocation但不使用默认路径

您还可以在app/config/view.php

'paths' => array(),

然后在任何情况下(前端和管理员)都使用View::addLocation

And then use View::addLocation in any case (frontend and admin)

View::addLocation(app_path().'/views');
View::addLocation(app_path().'/admin/views');

这篇关于如何在laravel中设置视图文件路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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