Search code examples
ruby-on-railslazy-loadinghaml

Using data attribute with rails image_tag and haml


I am trying to use Echo.js lazyloader.

To do so, I need to use a data attribute which will contain the path to my image to lazy load, such as:

<img src="/assets/images/placeholder.png" alt="" data-echo="/assets/images/myImage.jpg">

I am using rails and haml. According to several answers here, I should translate the plain html by: (but they don't specify what happens when the data links to an image path)

= image_tag("placeholder.png", :data => { "echo" => "/assets/images/myImage.jpg"})

OR

= image_tag("placeholder.png", "data-echo" => "/assets/images/myImage.jpg")

The placeholder.png image is displayed but myImage is never loaded.

When using the inspector, it doesn't seem that the myImage path is recognised as a path to an image.

Any ideas? Alternatively if you could suggest a lazy loader that doesn't rely on data- attributes and works with rails and haml, this would be great. Thanks


Solution

  • You need to use the rails assets helper on your placeholder too

    = image_tag("placeholder.png", data: { "echo" => image_path("myImage.jpg") })