现在的位置: 首页 > 综合 > 正文

rails标签值content_tag

2012年02月13日 ⁄ 综合 ⁄ 共 1871字 ⁄ 字号 评论关闭

 今天阅读《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.rb
module ApplicationHelper
  def hidden_div_if(condition, attributes = {}, &block)
    if condition
      attributes["style" ] = "display: none"
    end
    content_tag("div" , attributes, &block)
  end
end

主要是对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>

抱歉!评论已关闭.