rails標籤值content_tag

來源:互聯網
上載者:User

 今天閱讀《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>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.