开发者

On how views should get their variables

In a world of best practices, when do you let the view inherit the instance variables of the controller, and w开发者_如何学编程hen do you explicitly pass them in in the locals hash?


Any instance variables you define in your controller will automatically propagate to the view, so there's no need to pass them in explicitly. This works for not just your initial view, but also any partials rendered in the process.

You'll want to send in :locals variables when you're calling the same partial but need it to render different things that can't be accommodated with :object or :collection.

Here's an example of improperly using instance variables:

# Bad form
<%- @foo = 'example1' %>
<%= render(:partial => 'bar') %>
<%- @foo = 'example2' %>
<%= render(:partial => 'bar') %>

A better way is this:

<%= render(:partial => 'bar', :locals => { :foo => 'example1' }) %>
<%= render(:partial => 'bar', :locals => { :foo => 'example2' }) %>

The difference is that you'll see the variable in the partial as foo instead of @foo. Keep in mind that local variables may be undefined unless they are passed in which can cause trouble, so test thoroughly.


Good practice is to set variables in your controllers.

You shouldn't pass them from contoller because they will be visible automatically

#your_controller
@name = "Pedro"

#your view
Hello, <%= @name %>!
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜