Reputation: 20844
I starded to use HAML and I ran into a problem.
I need to put the image_path()
url in an elements data-attribute
.
Let's say that my image is app/assets/images/foo/bar/image.png
.
I figured out how to get the image_path
, for example
%h1 #{image_path ("foo/bar/image.png")}
/ will return
/assets/foo/bar/image-944cf331269515d31d4ab23897df6c217e4593a942af756d4433a4987961cc29.png
Which is good. Now I want to put this string into an element's data attribute, for example on h1
.
This is what I'd tried:
%h1{data: {'foo' => #{image_path ("foo/bar/image.png")} }}
/ returns an error
%h1{data: {'foo' => '#{image_path ("foo/bar/image.png")}' }}
/ returns
/ <h1 data-foo="#{image_path ('foo/bar/image.png')}"></h1>
This is what I'm looking for:
<h1 data-foo="/assets/foo/bar/image-944cf331269515d31d4ab23897df6c217e4593a942af756d4433a4987961cc29.png"></h1>
What is the right way to do this?
Thanks
Upvotes: 0
Views: 498
Reputation: 2280
Youre almost close, but maybe you dont know the difference of 'string' and "string".
In Ruby a string with 'string' wont replace anything. You need to call a string with "string" and you can use inside #{} to use ruby code in that string
test the following in your console
"#{1+1}" # outputs "2"
'#{1+1}' # outputs "#{1+1}"
now back to your problem:
%h1{data: {'foo' => '#{image_path ("foo/bar/image.png")}' }}
change to
%h1{data: {'foo' => "#{image_path ('foo/bar/image.png')}" }}
but you dont need those string manipulation, you can go straight for
%h1{data: {'foo' => image_path ("foo/bar/image.png") }}
or if you use ruby 2.2.1 you can go even more straight
%h1{data: {"foo": image_path ("foo/bar/image.png") }}
or to keep it totally short and more readable
%h1{"data-foo": image_path ("foo/bar/image.png")}
In Ruby 2.2.1 the behavior of hashes changed a little
2.1.2 :008 > {"foo": "bar"}
SyntaxError: (irb):8: syntax error, unexpected ':', expecting => {"foo": "bar"}
^
2.2.1 :003 > {"foo": "bar"}
=> {:foo=>"bar"}
thats the reason why the last 2 options i suggested are only working in 2.2.1
Upvotes: 2