开发者

get template vars inside helper

Can I get a local template var from a template in the helper?

test.html.erb:

<% my_test_var = 'wonderful' %>
<%= my_output %> 

test_helper.rb:

def my_output
  return @template[:my_test_var]
end开发者_StackOverflow社区

Of course @template doesn't exist. Is there a way to get it (not global with @).

Regards!

Edit:

The template test.html.erb is called a a partial render, with local variable:

render 'test', :locals => { :my_test_var = 'hallo'}

I need this passed variable in my helper.


If you want the template variables accessible in the helpers without having to pass them as arguments, the only way I know is to make them instance variables.

<% @my_test_var = 'wonderful' %>
<%= my_output %> 

def my_output
  return @my_test_var
end

This is not recommended though. Ideally, instance variables should be defined in controllers and used in the views. I'm not sure why you can't just pass the variable to the helper method. If that wasn't a requirement then I support krusty.ar's answer.


Helpers are normal methods, you can just do something like:

<% my_test_var = 'wonderful' %>
<%= my_output(my_test_var) %> 

test_helper.rb:

def my_output output
  return output
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜