Using a Haml object reference, for example. % DIV [@user]

Haml has a nice Object Link function where I can do something like this:

%div[user]= user.name 

And it generates something like this:

 <div id="user_42" class="user">Billy</div> 

Sometimes I want to create a binding to this element, for example:

 <a href="#user_42">Link to Billy</a> 

How do I do this in Haml? Is there an easier way than this ?:

 %a{ :href=> "#user_#{user.id} } Link to Billy 

Edit: Can it be done with Haml's automatically enabled helpers ?

+4
source share
1 answer

There is no built-in way to do this that I know of. I would probably create a helper method if it does a lot of things.

 def anchor_to(link_text, object) link_to(link_text, "##{object.class.name.underscore}_#{object.id}") end 

You can make the method more complicated if you need to handle more cases (passing parameters to link_to, etc.), but something simple would clear them. Link building will:

 = anchor_to("Link to Billy", @user) 

If you want to use Haml helpers, you can do something very similar (but much more confusing):

 def anchor_to(link_text, object) capture_haml do haml_tag :a, 'Link to Billy', href: "##{object.class.name.underscore}_#{object.id}" end end 

Although it should be warned that the underscore method will not be available if you do this outside of Rails (this is the only reason I can think of avoiding the link_to helper).

+2
source

Source: https://habr.com/ru/post/1386180/


All Articles