今天閱讀《Agile Web Development with Rails》時碰到下面的一段代碼比較疑惑
#Download depot_n/app/views/layouts/application.html.erb<%= hidden_div_if(@cart.line_items.empty?, :id => "cart" ) do %> <%= render @cart %><% end %>#Download depot_n/app/helpers/application_helper.rbmodule ApplicationHelper def hidden_div_if(condition, attributes = {}, &block) if condition attributes["style" ] = "display: none" end content_tag("div" , attributes, &block) endend
主要是對content_tag標籤和&block合用不怎麼明白,先去看看源碼上的說明文檔。
1 # Returns an HTML block tag of type +name+ surrounding the +content+. Add
2 # HTML attributes by passing an attributes hash to +options+.
3 # Instead of passing the content as an argument, you can also use a block
4 # in which case, you pass your +options+ as the second parameter.
5 # Set escape to false to disable attribute value escaping.
6 #
7 # ==== Options
8 # The +options+ hash is used with attributes with no value like (<tt>disabled</tt> and
9 # <tt>readonly</tt>), which you can give a value of true in the +options+ hash. You can use
10 # symbols or strings for the attribute names.
11 #
12 # ==== Examples
13 # content_tag(:p, "Hello world!")
14 # # => <p>Hello world!</p>
15 # content_tag(:div, content_tag(:p, "Hello world!"), :class => "strong")
16 # # => <div class="strong"><p>Hello world!</p></div>
17 # content_tag("select", options, :multiple => true)
18 # # => <select multiple="multiple">...options...</select>
19 #
20 # <%= content_tag :div, :class => "strong" do -%>
21 # Hello world!
22 # <% end -%>
23 # # => <div class="strong">Hello world!</div>
從上述我們可以看到content_tag("div" , attributes, &block)中的div為標籤資訊,attributes為style資訊,那麼&block是什麼意思呢?
在看個樣本
1 #http://api.rubyonrails.org/classes/ActionView/Helpers/RecordTagHelper.html
2
3 div_for(record, *args, &block)
4
5 Produces a wrapper DIV element with id and class parameters that relate to the specified Active Record object. Usage example:
6
7 <%= div_for(@person, :class => "foo") do %>
8 <%=h @person.name %>
9 <% end %>
10
11 produces:
12
13 <div id="person_123" class="person foo"> Joe Bloggs </div>
大概的意思明白了,content_tag("div" , attributes, &block)這句話就可以翻譯成下面的代碼
<div id=“cart">
<% render @cart%>
</div>