admin管理员组

文章数量:1433480

In Rails, the mon idiom for page-specific Javascript is:

(layout)

<head>
  <% yield :javascript %>
</head>

(view)

<% content_for :javascript do %>
  <script type="text/javascript">
    $().whatever;
  </script>
<% end %>

I hate repeating the script tags. Is there any reason why the following is a bad idea?

(layout)

<head>
  <script type="text/javascript">
    <% yield :javascript %>
  </script>
</head>

(view)

<% content_for :javascript do %>
    $().whatever;
<% end %>

In Rails, the mon idiom for page-specific Javascript is:

(layout)

<head>
  <% yield :javascript %>
</head>

(view)

<% content_for :javascript do %>
  <script type="text/javascript">
    $().whatever;
  </script>
<% end %>

I hate repeating the script tags. Is there any reason why the following is a bad idea?

(layout)

<head>
  <script type="text/javascript">
    <% yield :javascript %>
  </script>
</head>

(view)

<% content_for :javascript do %>
    $().whatever;
<% end %>
Share Improve this question asked May 10, 2011 at 14:31 Jay LevittJay Levitt 1,7201 gold badge21 silver badges28 bronze badges 1
  • You can put a <script> tag anywhere in the <body> and it will execute. Is there a particular reason you want to put it in the <head>? – Austin Taylor Commented May 10, 2011 at 14:59
Add a ment  | 

3 Answers 3

Reset to default 7

I agree that it's what is most specific to your use case. Generally, when I use the <% yield :javascript %>, it's purpose is to add in page specific libraries, which would be a limitation to the approach you proposed. If you want to support both, I have done the following:

(layout)

<head>
  <% yield :javascript_libraries %>
  <script type="text/javascript">
    <% yield :javascript %>
  </script>
</head>

(view)

<% content_for :javascript do %>
    $().whatever;
<% end %>
<% content_for :javascript_library do %>
    <%= javascript_include_tag 'page-specific.js' %>
<% end %>

Of course most people put javascript libraries at the bottom for optimization of page loading, so then you could just move it in your layout.

Idioms are great and all, but what matters most is you and your teams productivity and ability to maintain things, if you're OK with it I don't see any problem with it either. That said I've done this before and also seen it done in projects, although now I usually put it in a script file unless I absolutely have to have it in the specific page.

If you want to simplify your views, I highly remend HAML (and it's sister SASS for CSS). There is a slight learning curve and you may not want to convert all your existing views at once, but I doubt that you'll ever want to go back to the ugly mess of ERB.

In HAML, this would look like:

= content_for :head do
  :javascript
    $().whatever;

本文标签: javascriptRails viewscontentfor and DRYnessStack Overflow