开发者

Javascript, Rails views, content_for and DRYness

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

(layout)

<head>
  <% yield :javascript %>
</hea开发者_StackOverflowd>

(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 %>


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 recommend 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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜