HAML中Javascript中的Ruby方法 [英] Ruby methods within Javascript within HAML

查看:79
本文介绍了HAML中Javascript中的Ruby方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个jQuery脚本,它向表单添加一个新字段,该字段包含来自数组的动态信息。问题是我无法弄清楚如何添加一个array.each来填充javascript中select字段的选项而不会破坏HAML缩进并导致错误。

I have a jQuery script that adds a new field to a form, and this field contains dynamic information from an array. The problem is that I can't figure out how to add an array.each to populate the options of the select field within the javascript without breaking the HAML indentation and causing errors.

这是我最好的尝试不起作用:

Here is my best attempt that does not work:

%script(type="text/javascript")  
  $('#mylink').click(function() {  
  $('#mylink').after('<select>  
  - myarray.each do |options|  
     <option value="#{options.id}">#{options.name}</option>  
  </select>);  
  )};

还尝试使用:javascript过滤器,没有运气。

Also tried it with the :javascript filter with no luck.

推荐答案

通常情况下,如果haml中的某些内容很痛苦,那就意味着你应该将一个棘手的位重构为一个帮助器或者部分地调用它。

Usually, if something is a pain in haml, it means you should refactor the the tricky bit to a helper or partial and call that.

// some_helper.rb
def new_snazzy_select_tag(options = [])
  select_tag 'tag_name_here', options.map { |option| [option.id, option.name] }
end

另外,你应该使用:javascript 过滤器以呈现javascript,因为它会将它放在脚本标记中并允许缩进。

Also, you should use the :javascript filter to render javascript since it will put it in a script tag for you and allow indentation.

最后,您可以在haml的任何地方使用#{ruby_expression} ,包括:javascript 过滤器,这在您需要时非常方便将ruby表达式的结果输出到不直接包含html元素内容的地方。

Lastly, you can use #{ruby_expression} anywhere in haml, including :javascript filters, which is very handy when you need to output the result of ruby expressions to places that are not directly contents of html elements.

// some_view.html.haml
:javascript
  $('#mylink').click(function() {  
    $('#mylink').after("#{escape_javascript new_snazzy_select_tag(myarray)}");
  };

这篇关于HAML中Javascript中的Ruby方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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