Ruby-on-rails 如何将变量传递给 render_to_string?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3714198/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to pass variables to render_to_string?
提问by Arty
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?
但是当在模板中访问@sender 时,结果是 nil:NilClass。仔细检查我是否通过了正确的变量,这完全没问题。也许还有其他方法可以将变量传递给 render_to_string?
回答by Peter Brown
It might be the syntax you're using. Try using the :localsargument:
这可能是您正在使用的语法。尝试使用:locals参数:
@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.
然后您只需要访问sender(没有@)作为模板内的局部变量。
回答by Adit Saxena
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 => valuebit.
请介意:@user => value。
In Rails 5 (atm in beta):
在 Rails 5 中(测试版中的 atm):
ApplicationController.render(
file: 'path',
assigns: { foo: 'bar' }
)
回答by Manish Prajapat
Try this:
尝试这个:
ac = ActionController::Base.new()
ac.render_to_string(:partial => 'path to your partial',:locals => {:varable => your variables})
回答by vladCovaliov
In rails 4.0.2 this worked:
在 rails 4.0.2 这工作:
render_to_string(partial: 'path/to/partial', locals: { argument: 'value'}
回答by Gaurav Agarwal
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 中呈现不同格式的部分。真正对我有用的是:
render_to_string(:partial => 'partial_file.html', :locals => {:variable => variable}, :format => :html)
render_to_string(:partial => 'partial_file.html', :locals => {:variable => variable}, :format => :html)
where the name of the file was _partial_file.html.erb.
文件名在哪里_partial_file.html.erb。

