0

如何在 Rails 中为 HAML 定义一个助手来定义链接href='javascript:void(0)'

即这个的简写:

%a.link#somelink(href="javascript:void(0)") Link to Foo

希望比这更整洁:

- js_link {:class=>'link', :id=>'somelink'} "Link to Foo"

我的意思是 HAML 助手,而不是传统的 Rails 助手。我希望有类似的东西:

%js.link#somelink Link to Foo
4

1 回答 1

1

I think you are going to have a hard time with this. The simplest you could make it would probably be something like

#somelink.link
  - js_link 'Link to Foo'

But this would add the id and class attributes to a div surrounding your link rather than directly on it. If the selectors are for CSS or jQuery purposes, you might get away with leaving the attributes off altogether and using the surrounding element information to access the links:

#list-of-links
  %a{href: "javascript:void(0);"}
  %a{href: "javascript:void(0);"}
  %a{href: "javascript:void(0);"}

And in JavaScript:

jQuery('#list-of-links a').on('click', function() { return doSomething(); });

All this being said, it is possible to create a custom filter, similar to :css or :script for Haml with something like

Haml::Filters.register_tilt_filter "JavaScriptLink"

But for this to work, you would have to define your own "JavaScriptLink" Tilt template system, and even then, I'm not sure it would work or look any prettier.

于 2013-04-17T03:34:16.717 回答