Any way to avoid haml code duplication without creating new file?

删除回忆录丶 提交于 2019-12-11 04:34:26

问题


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?


回答1:


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")



回答2:


- (@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")


来源:https://stackoverflow.com/questions/16927113/any-way-to-avoid-haml-code-duplication-without-creating-new-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!