循环不能在haml中工作,但在html.erb中工作

时间:2014-04-30 11:10:21

标签: ruby-on-rails ruby-on-rails-4 haml

非常讨厌,

什么都不显示

- calendar @date do |date|
  = date.day

但haml的输出符合我的预期

  <%= calendar @date do |date| %>
    <%= date.day %>
  <% end %>

这是我的帮助源代码。

module CalendarHelper
  require 'pry'

  def widget
    concat link_to("Hello", '')
    concat " "
    concat link_to("Bye", '')
  end
  def calendar(date = Date.today, &block)
    cal_tbl = Calendar.new(self, date, block).table
    # content_tag :div do
    #   cal_tbl
    # end
    # return cal_tbl
  end

  class Calendar < Struct.new(:view, :date, :callback)
    HEADER = %w[Sunday Monday Tuesday Wednesday Thursday Friday Saturday]
    START_DAY = :sunday

    delegate :content_tag, to: :view

    def table
      content_tag :table, class: "calendar" do
        header + week_rows
      end
    end

    def header
      content_tag :tr do
        HEADER.map { |day| content_tag :th, day }.join.html_safe
      end
    end

    def week_rows
      weeks.map do |week|
        content_tag :tr do
          week.map { |day| day_cell(day) }.join.html_safe
        end
      end.join.html_safe
    end

    def day_cell(day)
      content_tag :td, view.capture(day, &callback), class: day_classes(day)
    end

    def day_classes(day)
      classes = []
      classes << "today" if day == Date.today
      classes << "notmonth" if day.month != date.month
      classes.empty? ? nil : classes.join(" ")
    end

    def weeks
      first = date.beginning_of_month.beginning_of_week(START_DAY)
      last = date.end_of_month.end_of_week(START_DAY)
      (first..last).to_a.in_groups_of(7)
    end
  end
end

enter image description here

3 个答案:

答案 0 :(得分:2)

根据haml Git,

  

连字符( - ),将运行代码但不输出结果

     

等号(=),将输出代码的结果

所以它应该是

= calendar @date do |date|
  = date.day

答案 1 :(得分:2)

这样做:

- calendar @date do |date|
  = date.day

HAML到HTML的翻译遵循这个惯例。应该运行且未显示的rails代码以-字符开头,相当于HTML中的<% rails code%>
HAML中的=等同于HTML <%= rails code %>,自动生成结束<%end%>以响应do rails代码。

答案 2 :(得分:0)

这样做

= calendar @date do |date|
  = date.day