41

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?

Arty
  • 5,923
  • 9
  • 39
  • 44

5 Answers5

55

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.

mwfearnley
  • 3,303
  • 2
  • 34
  • 35
Peter Brown
  • 50,956
  • 18
  • 113
  • 146
  • 6
    Just noticed you were trying to access sender as `@sender` in your view. Not sure about your original code, but if you use the locals syntax, it will be a local variable (not an instance variable) and will be accessed without the `@` – Peter Brown Sep 15 '10 at 12:53
  • Your solution actually work. You can pass locals as you said and access them as local variables, not instance variables. – MrYoshiji Dec 04 '12 at 15:48
  • 11
    I've been trying to use `render_to_string` from model. In order to use with as instance variable, I had to do `ActionController::Base.new.render_to_string(:template => "template", :locals => {:@sender => sender})` – Jason Kim May 15 '13 at 02:08
21

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

Community
  • 1
  • 1
Adit Saxena
  • 1,617
  • 15
  • 25
  • Doesn't work in the latest 4-2-stable https://github.com/rails/rails/commit/4c46a15e0a7815ca9e4cd7c7fda042eb8c1b7724#commitcomment-41917002 – Sergey Alekseev Aug 31 '20 at 16:03
5

Try this:

ac = ActionController::Base.new()  
ac.render_to_string(:partial => 'path to your partial',:locals => {:varable => your variables})
dario
  • 5,149
  • 12
  • 28
  • 32
2

In rails 4.0.2 this worked:

render_to_string(partial: 'path/to/partial', locals: { argument: 'value'}
vladCovaliov
  • 4,333
  • 2
  • 43
  • 58
2

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.

Gaurav Agarwal
  • 14,664
  • 4
  • 29
  • 41