30 Mar 2010

在rails中不同的view不同皮肤下的js,css,注入js和css到head区域

Share

利用layout可以很好实现这个需求.

在ApplicationHelper内加入如下代码:

def require_js(path)
    content_for :header_js do
      include_js_tag path
    end
  end

  def require_css(path)
    content_for :header_css do
      include_css_tag path
    end
  end

  def include_js_tag(path)
    if not path.starts_with?("http:")
      path = "/themes/#{@setting[:theme]}/javascripts/" + path
    end
    javascript_include_tag path
  end

   def include_css_tag(path)
    if not path.starts_with?("http:")
      path = "/themes/#{@setting[:theme]}/stylesheets/" + path
    end
    stylesheet_link_tag path
  end

(如果你要直接在view或者layout内引入css则可以<%= include_css_tag "global.css" %>,这样生成的路径是带有皮肤目录的)

接下来,修改你的layout的head,加入如下代码:

<%= yield :header_js %>
<%= yield :header_css %>

然后在需要引入js的View内

<% require_js "jquery/jquery.tools.min.js" %>
<% require_js "jquery/jquery.colorbox.min.js" %>

最后run一下,你会看到会在html的head内生成如下html

<script src="/themes/2010v1/javascripts/jquery/jquery.tools.min.js?1269949149" type="text/javascript"></script>
<script src="/themes/2010v1/javascripts/jquery/jquery.colorbox.min.js?1269949147" type="text/javascript"></script>

 

 

comments powered by Disqus