render_to_string in lib class not working

两盒软妹~` 提交于 2019-12-03 04:57:10
ac = ActionController::Base.new()
ac.render_to_string(:partial => '/path/to/your/template', :locals => {:varable => somevarable})
Germano

I had problems with a undefined helper method then I used ApplicationController

ApplicationController.new.render_to_string

render_to_string is defined in ActionController::Base. Since the class/module is defined outside the scope of the Rails controllers the function is not available.

You are going to have to manually render the file. I don't know what you are using for your templates (ERB, Haml, etc.). But you are going to have load the template and parse it yourself.

So if ERB, something like this:

require 'erb'

x = 42
template = ERB.new <<-EOF
  The value of x is: <%= x %>
EOF
puts template.result(binding)

You will have to open the template file and send the contents to ERB.new, but that an exercise left for you. Here are the docs for ERB.

That's the general idea.

You could turn your template.xml.builder into a partial (_template.xml.builder) and then render it by instantiating an ActionView::Base and calling render

av = ActionView::Base.new(Rails::Configuration.new.view_path)
av.extend ApplicationController.master_helper_module
xml = av.render :partial => 'something/template'

I haven't tried it with xml yet, but it works well with html partials.

Rails 5

render_to_string and others are now available as class methods on the controller. So you may do the following with whatever controller you prefer: ApplicationController.render_to_string

I specifically needed to assign a dynamic instance variable for the templates based on an object's class so my example looked like:

ApplicationController.render_to_string(
  assigns: { :"#{lowercase_class}" => document_object },
  inline: '' # or whatever templates you want to use
)

Great blog post by the developer who made the rails PR: https://evilmartians.com/chronicles/new-feature-in-rails-5-render-views-outside-of-actions

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