1.index.html
My Blog
<% @posts.each do |post| %><%= link_to 'Edit', edit_post_path(post) %> <%= link_to 'Destroy', post, confirm: 'Are you sure?', method: :delete %> <% end %><%= link_to_unless_current post.title,post %>
<%= simple_format post.content %>
<%= link_to 'New Post', new_post_path %>
2.show.html
<%= link_to 'Edit', edit_post_path(@post) %> <%= link_to 'Destroy', @post, confirm: 'Are you sure?', method: :delete %><%= link_to_unless_current @post.title,@post %>
<%= simple_format @post.content %>
显然2段代码有重复,可以利用 render :partial 实现代码复用
如下:
1.新建一个_post.html.erb文件,复制代码:
<%= link_to 'Edit', edit_post_path(post) %> <%= link_to 'Destroy', post, confirm: 'Are you sure?', method: :delete %> <% end %><%= link_to_unless_current post.title,post %>
<%= simple_format post.content %>
2.修改后Index.html
My Blog
<% @posts.each do |post| %> <%= render :partial => post }%> <% end %>
<%= link_to 'New Post', new_post_path %>
3.修改后show.html
<%= render :partial => @post %>
上面是常规做法,render :partial 会去view文件夹找_post.html.erb文件,然后把参数传进去。
但是如果_post.html.erb文件名和我传进去的参数名 不一致怎么办?
修改_post.html.erb文件名为_newPost.html.erb
index.html代码修改如下:
<%= render :partial => "newPost", :locals => { :post => @post }
show.html代码修改如下:
<%= render :partial => "newPost", :locals => { :post => post }
newPost就是 _newPost.html.erb
:post就是 _newPost.html.erb的变量名
后面的值就是你需要传进去的变量
参考: http://qing.weibo.com/1848718461/6e31347d330009t5.html