具有相同内容的HAML条件缩进link_to

时间:2017-09-05 12:52:21

标签: ruby-on-rails haml

我在HAML文件中有这个条件,但看起来不太漂亮:/

- if @receiver.type == "Admin"
  = link_to administrator_messages_url, style: "font-family:'Source Sans Pro', sans-serif;color:#676767;color:#2199e8;font-family:Helvetica, Arial, sans-serif;font-size:16px;font-weight:bold;color:#fefefe;text-decoration:none;display:inline-block;padding:8px 16px 8px 16px;border:0 solid #2199e8;border-radius:3px;border:0 solid #af0000;border-radius:5px;" do
    View Messages
    %i.fa.fa-commenting{"aria-hidden" => "true"}
- else
  = link_to messages_url, style: "font-family:'Source Sans Pro', sans-serif;color:#676767;color:#2199e8;font-family:Helvetica, Arial, sans-serif;font-size:16px;font-weight:bold;color:#fefefe;text-decoration:none;display:inline-block;padding:8px 16px 8px 16px;border:0 solid #2199e8;border-radius:3px;border:0 solid #af0000;border-radius:5px;" do
    View Messages
    %i.fa.fa-commenting{"aria-hidden" => "true"}

如何防止重复该病症的内容?

2 个答案:

答案 0 :(得分:1)

尝试:

= link_to @receiver.type == 'Admin' ? administrator_messages_url : messages_url, style: "font-family:'Source Sans Pro', sans-serif;color:#676767;color:#2199e8;font-family:Helvetica, Arial, sans-serif;font-size:16px;font-weight:bold;color:#fefefe;text-decoration:none;display:inline-block;padding:8px 16px 8px 16px;border:0 solid #2199e8;border-radius:3px;border:0 solid #af0000;border-radius:5px;" do
  View messages
  %i.fa.fa-commenting{"aria-hidden" => "true"}

答案 1 :(得分:1)

一种技术是从视图中提取分支。视图不是逻辑的最佳位置。即使是与表现相关的逻辑也最好放在别处(至少是帮助者)。

# helper
module ReceiverHelper
  def receiver_url(receiver)
    receiver.type == 'Admin' ? administrator_messages_url : messages_url
  end
end

然后在视图中

  = link_to receiver_url(@receiver), style: "font-family:'Source Sans Pro', sans-serif;color:#676767;color:#2199e8;font-family:Helvetica, Arial, sans-serif;font-size:16px;font-weight:bold;color:#fefefe;text-decoration:none;display:inline-block;padding:8px 16px 8px 16px;border:0 solid #2199e8;border-radius:3px;border:0 solid #af0000;border-radius:5px;" do
    View Messages
    %i.fa.fa-commenting{"aria-hidden" => "true"}