在Rails中需要javascript和CSS,而不直接将代码注入HEAD元素
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在Rails中需要javascript和CSS,而不直接将代码注入HEAD元素相关的知识,希望对你有一定的参考价值。
I used to directly inject javascript and CSS into my HEAD elements just like you see in all of the tutorials online and in books. Recently I decided to try a different approach, and I feel this is more in keeping with the ruby and rails "declaration" syntax. It has the added benefit of promoting unobtrusive javascript coding and factoring out page-specific CSS into its own file.
[application_helper.rb] module ApplicationHelper def requires_javascript(path) content_for :page_dependencies do javascript_include_tag path end end def requires_stylesheet(path) content_for :page_dependencies do stylesheet_link_tag path end end end [my_layout.html.erb] <html> <head> <%= yield :page_dependencies %> ... </head> ... </html> [my_view.html.erb] <% requires_javascript "my-view-specific-javascript" %> <% requires_stylesheet "my-view-specific-stylesheet" %>
以上是关于在Rails中需要javascript和CSS,而不直接将代码注入HEAD元素的主要内容,如果未能解决你的问题,请参考以下文章
在 Rails 中去除内联 CSS 和 JavaScript
在 Rails 中使用 HAML 而不是 ERB 时 CSS 未加载 (404)
如何在 css 类名中使用 javascript 变量并在 Rails 中通过 jquery 获取 css 颜色名