How to pass variables to render_to_string?

泄露秘密 提交于 2019-11-30 06:34:00

问题


Trying to do the following

@message = render_to_string ( :sender => sender, :template => "template" )          

But when accessing @sender in template it turns out to be nil:NilClass. Double checked if I pass the right variable and it's totally fine. Maybe there are other way to pass variables to render_to_string?


回答1:


It might be the syntax you're using. Try using the :locals argument:

@m = render_to_string :template => "template", :locals => {:sender => sender}

Then you just need to access sender (without an @) as a local variable inside the template.




回答2:


Here's Jason Kim's solution he wrote in a comment which worked for me:

ActionController::Base.new.render_to_string(
  "user_mailer/welcome_email.html.erb", locals: { :@user => user}
)

Please mind the :@user => value bit.


In Rails 5 (atm in beta):

ApplicationController.render(
  file: 'path',
  assigns: { foo: 'bar' }
)

More here




回答3:


Try this:

ac = ActionController::Base.new()  
ac.render_to_string(:partial => 'path to your partial',:locals => {:varable => your variables})



回答4:


I was trying to render a different format of partial in render_to_string. The thing which really worked for me was:

render_to_string(:partial => 'partial_file.html', :locals => {:variable => variable}, :format => :html)

where the name of the file was _partial_file.html.erb.




回答5:


In rails 4.0.2 this worked:

render_to_string(partial: 'path/to/partial', locals: { argument: 'value'}


来源:https://stackoverflow.com/questions/3714198/how-to-pass-variables-to-render-to-string

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