2017-04-06 73 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