【问题标题】:refactor conditions within haml view在haml视图中重构条件
【发布时间】:2009-09-02 13:59:43
【问题描述】:

除了无障碍标准不鼓励使用 指向当前页面的链接,我应该如何 重构以下视图代码?

#navigation
  %ul.tabbed
    - if current_page?(new_profile_path)
      %li{:class => "current_page_item"}
        = link_to t("new_profile"), new_profile_path
    - else
      %li
        = link_to t("new_profile"), new_profile_path

    - if current_page?(profiles_path)
      %li{:class => "current_page_item"}
        = link_to t("profiles"), profiles_path
    - else
      %li
        = link_to t("profiles"), profiles_path
    ...

谢谢。

【问题讨论】:

    标签: ruby-on-rails ruby haml


    【解决方案1】:
    # helpers
    def current_page_class(page)
      return :class => "current_page_item" if current_page?(page)
      return {}
    end
    
    -# Haml
    #navigation
      %ul.tabbed
        %li{current_page_class(new_profile_path)}
          = link_to t("new_profile"), new_profile_path
        %li{current_page_class(profiles_path)}
          = link_to t("profiles"), profiles_path
        ...
    

    【讨论】:

    • 太棒了!谢谢! P.S.:我想我可以丢弃函数中的最后一个返回,不是吗?
    • 确实如此;我添加它是为了与另一个 return 对称并强调哈希作为返回值存在。
    【解决方案2】:
    #navigation
      %ul.tabbed
        %li{:class => current_page?(new_profile_path) ? "current_page_item" :nil }
          = link_to t("new_profile"), new_profile_path
        %li{:class => current_page?(profiles_path) ? "current_page_item" :nil }
          = link_to t("profiles"), profiles_path
        ...
    

    【讨论】:

    • 谢谢!三元运算符更简洁,但我很想为此获得一个函数。
    【解决方案3】:

    对我来说,这似乎是一个很好的案例。

    【讨论】:

    • 人们,如果您要投反对票,请发表评论。否则你就不会加入讨论——你只是个混蛋。
    • Partials 在这里肯定会有所帮助,但你说得很含糊。关于将要进入部分的确切内容的建议会有所帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多