2017-04-06 62 views
0

我目前在使用HAML作爲模板語言的rails應用程序上構建了一個ruby。我正在創建一個條件,它定義了一個標籤,取決於它是否符合,否則它定義了一個不同的標籤。我知道我可以寫這樣的:HAML條件標籤

- if ordered 
    %ol 
- else 
    %ul 

但是,這不是特別乾燥,並要求我重複了大部分的代碼。有沒有一種非常直接的方法來解決這個問題?我應該看看Ruby的邏輯來找到它嗎?

謝謝

回答

0

如果你需要做的,我認爲有兩種方法不同的看法這個邏輯可以遵循:

1.部分並使其你需要這個的地方。如果你需要傳遞變量使用local_assigns

_my_list.html.haml

- if ordered 
    %ol 
- else 
    %ul 

使用它

render 'partials/my_list', ordered: ordered 

2.請您自己的助手

def my_list(ordered) 
    if ordered 
    content_tag(:ol, class: 'my-class') do 
     # more logic here 
     # use concat if you need to use more html blocks 
    end else 
    content_tag(:ul, class: 'my-class') do 
     # more logic here 
     # use concat if you need to use more html blocks 
    end 
    end 
end 

使用它

= my_list(ordered) 

你可以把你的命令變量視圖外和處理助手裏面的整個邏輯。

如果你問自己要使用什麼,那麼here的第一個答案是相當不錯的。

0

定義一個幫手。我們將介紹ordered選項來選擇標籤,其餘部分將傳遞給標籤。

# app/helpers/application_helper.rb 
module ApplicationHelper 
    def list_tag(ordered: false, **opts) 
    kind = ordered ? :ol : :ul 
    haml_tag kind, **opts do 
     yield 
    end 
    end 
end 

然後,

-# some_view.html.haml 
%p 
    Here's a list: 
- list_tag ordered: false, class: 'some_class' do 
    - @list.each do |item| 
    %li 
     = item