Including inline javascript using content_for in rails

后端 未结 2 1932
暗喜
暗喜 2020-12-23 15:22

I am using content_for and yeild to inject javascript files into the bottom of my layout but am wondering what the best practice is for including inline javascript. Specifi

2条回答
  •  粉色の甜心
    2020-12-23 15:38

    Here's a solution if you really want to keep the number of < script> tag minimal in your html and still be able to have your IDE highlight javascript. It's really useful with jquery if you want only one $(document).ready() call in your html or with facebook js api to call js when the api is loaded, etc...

    layout_helper.rb :

      def javascript_jquery_ready(script)
        content_for(:javascript_jquery_ready) {
          script .gsub(/(
    

    any view file:

    <% javascript_jquery_ready (capture do %>
      
    <% end) %>
    

    This solution enable me to keep my code organise and readable in my IDE since I don't need to create partial for every js code. Even if it change nothing for the end user the html result is cleaner.

提交回复
热议问题