Pedro
Pedro

Reputation: 33

Output content from render_to_string using global variable

I am inside a Controller where I have a method that saves information inside global variables like the following

@var = "test"

Now when I want to render the view file I am using the following code

MyController.new.render_to_string(:template => 'folder/file.erb', :layout => false)

The issue I'm having is that inside the file.erb it cant access the variable @var for some reason. The code goes as follows:

<% @var.each do |v| %>

<% end if [email protected]? %>

Which is returning null as it's content. How can I fix this?

Upvotes: 1

Views: 619

Answers (1)

Karol Wyliziński
Karol Wyliziński

Reputation: 66

I think you should pass it as a local: MyController.new.render_to_string(:template => 'folder/file.erb', :layout => false, :locals => { :var => @var )

Then it will be accessible as a local variable var (without @).

If you want to do some Rails magic, you should point an action where your @var is defined: MyController.new.render_to_string(:template => 'folder/file.erb', :layout => false, :action => 'your_action_name') so Rails will be able to reuse your variable in the view

Upvotes: 1

Related Questions