手把手教你学习ROR-2.View中的locals,as,object,layout以及FormHelper

手把手教你学习ROR-2.View中的locals,as,object,layout以及FormHelper

http://api.rubyonrails.org/classes/ActionView/PartialRenderer.html

1 locals,objects,as在partial中的使用

locals:
In a template for Advertise#accout
<%= render partial: "account", locals: { account: @buyer } %>
that means:render “advertiser/_account.html.erb” with @buyer passed in as the local variable account

as:
用于更换名字
<%= render partial: "account", object: @buyer, as: 'user' %> is same with
<%= render partial: "account", locals: { user: @buyer } %>


object:
<%= render partial: "account", object: @buyer %>
The :object option can be used to pass an object to the partial.the same as the partial template name.
If my partial template is named _user.html.erb then there will be a local variable named "user" defined in the template.

layout:
下面的例子阐述了layout的用法,相当于用layout的erb中嵌套使用user
<%# app/views/users/index.html.erb &>
Here's the administrator:
<%= render partial: "user", layout: "administrator", locals: { user: administrator } %>

<%# app/views/users/_user.html.erb &>
Name: <%= user.name %>

<%# app/views/users/_administrator.html.erb &>
<div id="administrator">
Budget: $<%= user.budget %>
<%= yield %>
</div>

(output)
Here's the administrator:
<div id="administrator">
Budget: $<%= user.budget %>
Name: <%= user.name %>
</div>

<%= render @products %> is same with
<%= render partial: "products/product", collection: @products %> is same with
<%= render partial: "product", collection: @products %>

2 FormHelper:

http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html

form_for
<%= form_for @post do |f| %>
<%=f.label :title,'Title'%>
<%=f.text_field :title%>
<%=f.text_area :body %>
<%=f.password_field :password %>
<%=f.email_field :email %>
<%=f.hidden_field(:user, :token) %>

<%=f.check_box :remember_me %>
<%=f.submit "Sign in" %>
<% end %>

原文地址:https://www.cnblogs.com/SoulSpirit/p/3336774.html