Rails 5 render a template located outside of the 'views' directory

余生颓废 提交于 2019-12-12 17:55:41

问题


The following code

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

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"

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?


回答1:


Start by appending the view path:

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

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

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

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




回答2:


You have to add the new folder to your configuration:

config.paths["app/views"].unshift(Rails.root.join("/vendor/myapp/views/myctrl").to_s)

Or your controller:

before_filter {
prepend_view_path(Rails.root.join("vendor/myapp/views/myctrl").to_s)
}

source



来源:https://stackoverflow.com/questions/40065805/rails-5-render-a-template-located-outside-of-the-views-directory

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