Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass variables to render_to_string?

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?

like image 350
Arty Avatar asked Sep 15 '10 02:09

Arty


5 Answers

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.

like image 71
Peter Brown Avatar answered Nov 18 '22 14:11

Peter Brown


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

like image 24
Adit Saxena Avatar answered Nov 18 '22 13:11

Adit Saxena


Try this:

ac = ActionController::Base.new()  
ac.render_to_string(:partial => 'path to your partial',:locals => {:varable => your variables})
like image 4
Manish Prajapat Avatar answered Nov 18 '22 13:11

Manish Prajapat


In rails 4.0.2 this worked:

render_to_string(partial: 'path/to/partial', locals: { argument: 'value'}
like image 2
vladCovaliov Avatar answered Nov 18 '22 14:11

vladCovaliov


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.

like image 2
Gaurav Agarwal Avatar answered Nov 18 '22 14:11

Gaurav Agarwal