Javascript、Rails 视图、content_for 和 DRYness
在 Rails 中,特定于页面的 Javascript 的常见习惯用法是:(
布局)
<head>
<% yield :javascript %>
</head>
(视图)
<% content_for :javascript do %>
<script type="text/javascript">
$().whatever;
</script>
<% end %>
我讨厌重复脚本标签。有什么理由说明以下是一个坏主意吗?
(布局)
<head>
<script type="text/javascript">
<% yield :javascript %>
</script>
</head>
(视图)
<% content_for :javascript do %>
$().whatever;
<% end %>
In Rails, the common 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 %>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我同意这是最适合您的用例的。一般来说,当我使用 <% yield :javascript %> 时,它的目的是添加页面特定的库,这将是对您提出的方法的限制。如果你想同时支持两者,我已经做了以下操作:
(布局)
(视图)
当然,大多数人将 javascript 库放在底部以优化页面加载,因此你可以将其移动到布局中。
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)
(view)
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.
如果你想简化你的观点,我强烈推荐 HAML (它是 CSS 的姐妹 SASS)。有一个轻微的学习曲线,你可能不想立即转变所有现有的观点,但我怀疑你是否会想回到 ERB 的丑陋混乱。
在 HAML 中,这看起来像:
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: