将html提取到辅助方法rails

时间:2013-09-09 18:40:29

标签: ruby-on-rails ruby

我的应用程序中有一个帮助程序,代码如下:

module ApplicationHelper
  def cms(key)
    if Text.find_by_key(key)
      Text.find_by_key(key).content
    else
      nil
    end
  end

  def cms2(key)
    if Text.find_by_key(key)
      Text.find_by_key(key)
    else
      nil
    end
  end
end

在我的视图文件中我有这个:

<%if cms('front2')==nil%>
    <%if admin_signed_in?%>
        <%=link_to "create", new_text_path(:key => 'front2')%>
    <%end%>
<%else%>
    <%=raw(cms('front2'))%>
    <%if admin_signed_in?%>
        <%=link_to("Edit", edit_text_path(cms2('front2')), :class=>"editcms")%>
    <%end%>     
<%end%> 

我想提取此代码的html部分,以便我可以调用这样的帮助器:

<%= new_method('front2') %>

1 个答案:

答案 0 :(得分:1)

# app/helpers/application_helper.rb
include ActionView::Helpers::UrlHelper 
module ApplicationHelper
  def cms(key, admin_signed_in)
    if key.nil?
        if admin_signed_in
            if Text.find_by_key(key)
              link_to 'create', new_text_path(:key => key)
            else
              nil
            end
        end
    else
        text = Text.find_by_key(key).content
        if admin_signed_in
            "#{text} #{link_to('Edit', edit_text_path(cms2(key)), :class => 'editcms')}".html_safe
        else
            text
        end
    end
  end
end

# in your view
<%= cms('front_2') %>