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 ?
In Haml, we write a tag by using the percent sign and then the name of the tag. This works for %strong , %div , %body , %html ; any tag you want. Then, after the name of the tag is = , which tells Haml to evaluate Ruby code to the right and then print out the return value as the contents of the tag.
Haml (HTML Abstraction Markup Language) is a templating system that is designed to avoid writing inline code in a web document and make the HTML cleaner. Haml gives the flexibility to have some dynamic content in HTML.
Haml is a markup language that's used to cleanly and simply describe the HTML of any web document, without the use of inline code. Haml functions as a replacement for inline page templating systems such as PHP, ERB, and ASP.
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}
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}"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With