如何使用if else条件减少重复的haml代码

时间:2015-07-19 14:32:04

标签: haml

很难在haml中编写if else,

它会使代码看起来嵌套和脏。

我可以更多地改进以下代码吗?

  - user_agent = UserAgent.parse(request.user_agent)
  - if user_agent.mobile?
    .page-header
      %h4
        = get_route_title(@from, @to)
        %small
          = [t(@interval, scope: "flights"),
             t(@interval, scope: "flights.interval"),
             ].join(" ")
    - @line_charts.each do |line_chart_content|
      .row.presentation{:style => "padding-left:5px;"}
        = show_line_chart(line_chart_content)

  - else
    .page-header
      %h1
        = get_route_title(@from, @to)
        %small
          = [get_date_range(@start_date, @start_date+1.month),
             t(@interval, scope: "flights"),
             t(@interval, scope: "flights.interval"),
             ].join(" ")
    - @line_charts.each do |line_chart_content|
      .row.presentation{:style => "padding-left:99px;"}
        = show_line_chart(line_chart_content)

1 个答案:

答案 0 :(得分:1)

- user_agent = UserAgent.parse(request.user_agent)
  - content_for :my_part do
    = get_route_title(@from, @to)
        %small
          = [t(@interval, scope: "flights"),
             t(@interval, scope: "flights.interval"),
             ].join(" ")
    - @line_charts.each do |line_chart_content|
      .row.presentation{:style => "padding-left:5px;"}
        = show_line_chart(line_chart_content)
  - if user_agent.mobile?
    .page-header
      %h4
        = yield :mypart
  - else
    .page-header
      %h1
        = yield :mypart