在子文件夹中的Rails中渲染MIME类型的模板,而无需在渲染调用中显式提供整个路径 [英] Render mime typed templates in Rails that are in a subfolder without explicitly providing the whole path in a render call

查看:73
本文介绍了在子文件夹中的Rails中渲染MIME类型的模板,而无需在渲染调用中显式提供整个路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用基于用户角色的Rails应用程序,该应用程序将根据给定的用户角色呈现不同的视图.这是通过使用自定义的mime类型来完成的.我是根据此处的堆栈溢出文章构建的. /p>

效果出色.您不需要,甚至不必在控制器中显式呈现相应的模板:

def index
    @projects = Project.all
end

代替:

def index
    @projects = Project.all
    respond_to do |format|
      format.html
      format.admin
    end
end

由于文件的mime类型结尾,控制器将自动呈现正确的模板.

我现在遇到的唯一问题是,我的视图文件夹有点被所有这些不同的模板弄得乱七八糟,我想根据它们的类型将它们分组和组织在子文件夹中. 假设我想创建一个名为"admin"的子文件夹,并将所有我的admin类型的文件放在此处.这导致不再找到文件,因为控制器不在子文件夹中寻找它们.因此,我得到模板丢失错误.

在保持控制器整洁的同时,是否有任何方法可以将它们组织在子文件夹中,即不必在渲染调用中明确声明模板的整个路径?

解决方案

我能够通过更改默认视图路径(如建议的here.

It works brilliantly. You don't even have to explicitly render the according templates in a controller:

def index
    @projects = Project.all
end

instead of:

def index
    @projects = Project.all
    respond_to do |format|
      format.html
      format.admin
    end
end

The controller will automatically render the correct template, thanks to the mime type ending of the file.

The only problem I'm having now is, that my view folder is kinda getting cluttered with all these different templates and I'd like to group and organize them in subfolders according to their type. Let's say I want to create a subfolder named "admin" and put all my admin typed files there. This leads to the files not being found anymore, because the controller doesn't look for them in the subfolder. Therefore I get a template missing error.

Is there any way to organize them in subfolders while keeping my controller clean, i.e. not having to explicitly state the whole path of the template in a render call?

解决方案

I was able to restructure the view folders by changing the default view path like suggested here.

这篇关于在子文件夹中的Rails中渲染MIME类型的模板,而无需在渲染调用中显式提供整个路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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