Any way to avoid haml code duplication without cre

2019-08-11 03:12发布

I have the following code in a .haml template file in a Sinatra app:

- if(@order == 'inverse') 
    - @list.reverse_each do |item| 
        .item
            %span.action-move(data-icon="o")
            .detail.title=item[0]
            .detail.content=item[1]
            %span.action-delete(data-icon="d")
- else 
    - @list.each do |item| 
        .item
            %span.action-move(data-icon="o")
            .detail.title=item[0]
            .detail.content=item[1]
            %span.action-delete(data-icon="d")

As you can see, 5 lines of code are identical. Is there a way that I can refactor this code to avoid the duplication here without creating an additional file to use as a partial?

2条回答
趁早两清
2楼-- · 2019-08-11 03:42

Off the top of my head - you could create a temp list that you would set in the conditionals and then loop through the temp list like so:

- if(@order == 'inverse')
  - temp = @list.reverse
- else 
  - temp = @list
- @temp.each do |item| 
  .item
    %span.action-move(data-icon="o")
    .detail.title=item[0]
    .detail.content=item[1]
    %span.action-delete(data-icon="d")
查看更多
我想做一个坏孩纸
3楼-- · 2019-08-11 03:42
- (@order == 'inverse' ? @list.reverse : @list).each do |item| 
  .item
    %span.action-move(data-icon="o")
    .detail.title=item[0]
    .detail.content=item[1]
    %span.action-delete(data-icon="d")

Or, as @matt suggests:

- (@order == 'inverse' ? @list.reverse_each : @list.each).each do |item| 
  .item
    %span.action-move(data-icon="o")
    .detail.title=item[0]
    .detail.content=item[1]
    %span.action-delete(data-icon="d")
查看更多
登录 后发表回答