Rails 5 渲染位于“views"目录之外的模板 [英] Rails 5 render a template located outside of the 'views' directory

查看:29
本文介绍了Rails 5 渲染位于“views"目录之外的模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码

def show
  render File.join(Rails.root, 'app', 'themes', 'default_theme', 'template'), layout: File.join(Rails.root, 'app', 'themes', 'default_theme', 'layout')
end

在 rails 4.2.x 中工作,但在使用 Rails 5.0.0 时输出以下错误

Works in rails 4.2.x but outputs the following error when using Rails 5.0.0

ActionView::MissingTemplate:
 Missing template vagrant/app/themes/default_theme/template with {:locale=>[:nl], :formats=>[:html], :variants=>[], :handlers=>[:raw, :erb, :html, :builder, :ruby]}. Searched in:
   * "/vagrant/app/views/themes/default_theme"
   * "/vagrant/app/views"
   * "/home/vagrant/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/bundler/gems/devise-ebe65b516b38/app/views"
   * "/home/vagrant/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/devise-i18n-1.1.0/app/views"

它看起来只在app/views/*"目录中搜索.有没有办法使用 rails 5.0.0 渲染位于views"目录之外的模板,使其像在以前的 Rails 版本中一样工作?

It looks like it is searching only inside the 'app/views/*' directory. Is there a way to render a template located outside of the 'views' directory using rails 5.0.0, so it works just like it used to in previous Rails versions?

推荐答案

从追加视图路径开始:

class ApplicationController
  prepend_view_path( Rails.root.join('app/templates') )
  # ...
end

然后您可以通过调用在 app/templates 中渲染模板:

You can then render templates in app/templates by calling:

render template: 'default_theme/template', 
       layout: 'default_theme/layout'

使用 template 选项告诉 rails 不要在路径后面附加控制器的名称.

Using the template option tells rails to not append the path with the name of the controller.

这篇关于Rails 5 渲染位于“views"目录之外的模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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