How to use HAML in a dynamic link?

I am trying to create a link using HAML that looks like

=link_to("Last updated on<%=@last_data.date_from.month %>",'/member/abc/def?month={Time.now.month}&range=xyz&year={Time.now.year}') 

It does not accept Ruby code and displays it as a string

Last update: <% = @ last_data.date_from.month%>

and the Time.now.month or Time.now.year function is also not executed in the URL.

How to pass Ruby code to url and string?

+8
ruby ruby-on-rails ruby-on-rails-3 haml
source share
3 answers

You should probably use something like this:

 = link_to("Last updated on #{@last_data.date_from.month}", "/member/abc/def?month=#{Time.now.month}&range=xyz&year=#{Time.now.year}") 

Note that in the second line you need to change ' to.' Also, if the link text becomes long, you can use something like this:

 = link_to("/member/abc/def?month=#{Time.now.month}&range=xyz&year=#{Time.now.year}") do Last updated on #{@last_data.date_from.month} 
+9
source share

Everything after = in HAML is a Ruby expression. Ruby does not interpolate strings as HAML does, it has its own way of interpolating it.

In Ruby, when you want to have the string value of some variable inside another string, you can do.

 "Some string #{Time.now}" 

So this should be:

 = link_to "Last updated on #{@last_data.date_from.month}", "/member/abc/def?month=#{Time.now.month}&range=xyz&year=#{Time.now.year}" 
+7
source share

A simple example with easy syntax:

  link_to "Profile #{rubycode}", "profile_path(@profile)/#{ruby_code}", class: "active" 
0
source share

All Articles