【问题标题】:if else errorif else 错误
【发布时间】:2009-09-20 19:26:08
【问题描述】:

这是我的代码。我对空格有疑问。我无法得到正确的一代

- if @lastday.nil? && @lastday != item.created_at.strftime("%d %b %Y")
  .daily-entry
    %h1.date
      =h item.created_at.strftime("%d")
      %span
        =h item.created_at.strftime("%b, %Y")
-else
  .entry
      %h1
        = link_to item.title, "/items/#{item.id}"

生成这是

<div class='daily-entry'> 
 <h1 class='date'> 
   20
   <span> 
    Sep, 2009
    </span> 
 </h1> 
</div> 
<div class='entry'> 
 <h1> 
  <a href="/items/15">xcvxcvx</a> 
 </h1>
</div>

但我想要一个 HTML

<div class='daily-entry'> 
 <h1 class='date'> 
   20
   <span> 
    Sep, 2009
    </span> 
 </h1> 
 <div class='entry'> 
   <h1> 
     <a href="/items/15">xcvxcvx</a> 
   </h1>
 </div>
</div>

.daily-entry

应该包含在条件中

如果条件为真

<div class='daily-entry'> 
 <h1 class='date'> 
   20
   <span> 
    Sep, 2009
    </span> 
 </h1>
 <div class='entry'> 
  <h1> 
   <a href="/items/15">xcvxcvx</a> 
  </h1>
 </div>
</div>

如果条件

<div class='entry'> 
 <h1> 
  <a href="/items/15">xcvxcvx</a> 
 </h1>
</div>

【问题讨论】:

    标签: ruby-on-rails ruby haml


    【解决方案1】:

    只需将if 移动到.daily-entry 内即可:

    .daily-entry
      - if @lastday.nil? && @lastday != item.created_at.strftime("%d %b %Y")
        %h1.date
          =h item.created_at.strftime("%d")
          %span
            =h item.created_at.strftime("%b, %Y")
      -else
        .entry
          %h1
            = link_to item.title, "/items/#{item.id}"
    

    【讨论】:

      【解决方案2】:

      你不想

      if !@lastday.nil?
      

      而不是

      if @lastday.nil?
      

      【讨论】:

        【解决方案3】:

        看起来您必须将条目复制为第一个剪辑:

        -if @lastday.nil? && @lastday != item.created_at.strftime("%d %b %Y")
          .daily-entry
            %h1.date
              =item.created_at.strftime("%d")
              %span= item.created_at.strftime("%b, %Y")
            .entry
              %h1= link_to item.title, "/items/#{item.id}"
        -else
          .entry
            %h1= link_to item.title, "/items/#{item.id}"
        

        应该有一种方法来解决这种重复,但我想不出它应该是什么 - 一个可能需要一个块的辅助函数。

        【讨论】:

        • 这不是一个干净的解决方案 :( 这是 rails-haml gem 的限制吗?
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-05-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-07-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多