How do I use HAML in a dynamic link?

20,780

Solution 1

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 string, it's necessary to change the ' to ". Also if the link text is getting 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}

Solution 2

Everything after the = in HAML is a Ruby expression. Ruby doesn't interpolate strings the way HAML does, it has own way of such interpolation.

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

"Some string #{Time.now}"

So, it 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}"
Share:
20,780
Arihant Godha
Author by

Arihant Godha

The more you sweat in training. The less you bleed in Battle

Updated on July 09, 2022

Comments

  • Arihant Godha
    Arihant Godha almost 2 years

    I am trying to create a link using HAML which looks like the this

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

    It is not taking the Ruby code and it is displaying that as a string

    Last updated on<%=@last_data.date_from.month %>

    and in the URL as well it is not taking the function Time.now.month or Time.now.year .

    How do I pass Ruby code in URL and in the string ?

  • Arihant Godha
    Arihant Godha over 11 years
    Hey thanks First part is working but in the URL I am still getting Time.now.year and Time.now.month
  • Jiří Pospíšil
    Jiří Pospíšil over 11 years
    Did you change the surroundings? I mean ' -> "
  • Jiří Pospíšil
    Jiří Pospíšil over 11 years
    Well you should :). If you have a string in ' ', it's not interpolated with any ruby expressions.
  • Arihant Godha
    Arihant Godha over 11 years
    The Url should look like this is it ? ,'/member/abc/def?month=#{Time.now.month}&range=xyz&year=#{T‌​ime.now.year}'