在rails中使用content_for包含内联javascript [英] Including inline javascript using content_for in rails

查看:111
本文介绍了在rails中使用content_for包含内联javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用content_for和yeild将javascript文件注入我的布局底部,但我想知道包含内联javascript的最佳做法是什么。具体来说,我想知道脚本类型声明的位置:

I am using content_for and yeild to inject javascript files into the bottom of my layout but am wondering what the best practice is for including inline javascript. Specifically I'm wondering where the put the script type declaration:

<% content_for :javascript do %> 
  <script type="text/javascript"> ... </script>
<% end %>

<% content_for :javascript do %> ... <% end %>
  <script type="text/javascript">
    <%= yield :javascript %>
  </script>
<% end %>

我现在正在使用第一个选项并想知道包含多个

I am using the first option now and wondering if it is bad to include multiple

一个视图中的声明。有时我会有部分导致这种情况。

declarations within one view. Sometimes I have partials that lead to this.

推荐答案

我更倾向于让布局的收益看起来像这样:

I much prefer to have the layout's yield look like this:

<html>
  <!-- other stuff -->
  <body>
   <!-- other stuff  -->
   <%= yield :javascript %>
  </body>
</html>

然后在视图中你可以写:

Then in a view you can write:

<% content_for :javascript do %>
  <script type='text/javascript'>
    function doMagic() {
      //Mind-blowing awesome code here
    }
  </script>

<% end %>

<!-- More view Code -->

<%= render :partial => "sub_view_with_javascript" %>

在部分_sub_view_with_javascript.html.erb中你也可以写:

And in the partial _sub_view_with_javascript.html.erb you can also write:

<% content_for :javascript do %>
  <script type='test/javascript'>
     function DoMoreMaths() {
       return 3+3;
     }
   </script>
<% end %>

我对这种方法的推理是yield和content_for在不同的文件中。为每个content_for 设置脚本标记并不是DRY,但是它允许语法高亮显示器识别每个文件中语言的变化并帮助我。

My reasoning for this approach is that the yield and content_for are in different files. It is not DRY to put the script tag in for every content_for but it allows the syntax highlighter to recognize the change in language in each file and helps me there.

如果你在一个文件中有多个content_for调用到同一个符号(在我们的例子中是:javascript)我会考虑将它们全部合并到最顶层,但它非常适合与partials一起使用。

If you have multiple content_for calls in a single file to the same symbol (in our case, :javascript) I would consider consolidating them all to the top one, but its perfect for use with partials.

HTML非常乐意拥有您想要的尽可能多的脚本块。唯一可能的问题是在使用firebug等开发人员工具中的代码时,需要花费更多的时间为您的函数找到正确的脚本块。当我需要设置一个javascript断点进行调试时,这只会发生在我身上。

And HTML is perfectly happy to have as many script blocks as you would like. The only possible gotcha is when working with the code in developer tools like firebug, it takes a little bit more time to find the right script block for your function. This only happens for me when I need to set a javascript breakpoint to debug.

这篇关于在rails中使用content_for包含内联javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆