Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use HAML in a dynamic link?

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 ?

like image 953
Arihant Godha Avatar asked Dec 27 '12 10:12

Arihant Godha


People also ask

How do I run a HAML code?

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.

What are HAML files used for?

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.

What is HAML in CSS?

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.


2 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 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}
like image 156
Jiří Pospíšil Avatar answered Oct 12 '22 23:10

Jiří Pospíšil


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}"
like image 45
Gosha A Avatar answered Oct 12 '22 23:10

Gosha A