asset_hash with variable in src

This will correctly hash the image:

<img src='/images/logo.png'/>

If I add a variable in the src, this doesn’t work:

<img src='#{cdn}/images/logo.png'/>

I know I could use asset_host with image_tag helper, but I also want to lazy load images, and I didn’t know how to use data-src attributes with that helper. Solution to either problem would be helpful. Thanks!

1 Like

use <%= cdn %> instead of #{cdn}

if you wanna use the image helper, you can add the data-src like this:

<%= image_tag img, :data-src=> varName %>

or

 <%= image_tag img, :data-src=> 'justSomeText' %>

I hope that helps

We took this one step further.

URLs that are on CDN are variables for a unique domain name (ie http://cdn.example.com rather than http://example.com) and then we do an after build script to replace all examples of the CDN domain name text with a NGINX SSI variable, so the final build outputs:

<img src='<!--# echo var="cdn_host" default="//example.com" -->/images/logo.png' />

This allows us to change out our CDN without rebuilding, or use the same build for production and qa environments with different CDNs, and use CDN anywhere in the build. (including JavaScript)