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
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;
本文标签: javascriptRails viewscontentfor and DRYnessStack Overflow
版权声明:本文标题:Javascript, Rails views, content_for and DRYness - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741888509a2403166.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论