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
3 Answers
Reset to default 7I 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;
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1741888510a4371766.html
评论列表(0条)