在 Rails 6 上渲染 js.erb 视图

aar*_*rio 3 ruby-on-rails

我在文件 APP/views/js/library.js.erb 文件中有一个视图,它包含:

bar: <%= raw @foo %>   
Run Code Online (Sandbox Code Playgroud)

在 Rails 4 上,我使用以下方法获取了该视图的内容:

av = ActionView::Base.new(Rails.root.join('app', 'views'))
av.assign({ foo: my_dynamic_variable })
av.render(template: 'js/library')
Run Code Online (Sandbox Code Playgroud)

但在 Rails 6 上我得到:

NoMethodError: undefined method `html_fallback_for_js' for 
"app/views/js/library":String
from /home/manuel/.rvm/gems/ruby-3.0.2/gems/actionview- 
6.1.4.1/lib/action_view/base.rb:264:in `in_rendering_context'
Run Code Online (Sandbox Code Playgroud)

小智 7

在 Rails 6.1 中:

lookup_context = ActionView::LookupContext.new(ActionController::Base.view_paths)

context = ActionView::Base.with_empty_template_cache.new(lookup_context, {}, nil)

renderer = ActionView::Renderer.new(lookup_context)

renderer.render(context, { file: 'app/views/template.html.erb' })
Run Code Online (Sandbox Code Playgroud)
  • ActionView::Renderer.new()需要一个lookup_context参数,render()方法需要一个上下文,所以我们首先设置它们
  • ActionView::Base是默认ActiveView上下文,必须用with_empty_template_cachemethod初始化,否则render()会报错
  • {},是必需的分配和控制器参数,在 Rails 5 中nil用于to {}默认nil
  • Rails 6.1 需要完整的文件路径文件:“app/views/template.html”,而 Rails 5 仅需要文件名