Bart Platak
Bart Platak

Reputation: 4475

Rails prevent HAML from escaping a link (w/ helper haml_tag)

I'm trying to create a simple menu and I came across this problem: HAML keeps escaping my links to html entities. I have a helper that is supposed to generate a menu:

def buildMainMenu(file=Rails.root.join("config","menu.yaml"))
    ... some operations ...

    link = url_for par.merge({:controller=>mitem["controller"], :action=>mitem["action"]})

    ... some more operations yay ...

    haml_tag :a, mitem["label"], :href=>link 
end

par is {"testPARAM1"=>"testVAL1","testPARAM2"=>"testVAL2"}

Sadly the output is

<a href='/test/test1?testPARAM1=testVAL1&amp;testPARAM2=testVAL2'>Test2</a>

I've looked for a while now and I can't seem to find how to force HAML to NOT escape my strings :(

Upvotes: 0

Views: 795

Answers (2)

Bart Platak
Bart Platak

Reputation: 4475

Just figured it out (I wish I've found it before spending over an hour on it but hey). For anyone interested:

There are two functions html_safe and raw that do the trick. Used as follow:

  • haml_tag :a, mitem["label"], :href=>link.html_safe
  • haml_tag :a, mitem["label"], :href=>raw(link)

Upvotes: 0

David Lesches
David Lesches

Reputation: 788

I know this isn't 100% what you are looking for, but personally I would refactor this - this is going to cause you headaches and anyway, rendering html within a helper isn't ideal at all.

I'd change the helper function to get your YAML file, or whatever is going on there, and output a final array with the correct items.

Make a _header.html.haml partial (put it in a directory 'shared'), the partial will call the helper function, get the array, and since you are in a view you can loop with normal techniques, and use link_to, etc, and all your problems are solved.

This is a much cleaner way of doing things.

Upvotes: 1

Related Questions