Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Render Images in Javascript with Rails 3.1

Rails 3.1 now requires you to use image_tag when rendering an image using the asset pipeline.

I have built endless scroll into my application and have put the code into a js.coffee file. I wish to render a spinning loading gif whilst more products are loaded. I cannot use image_tag here as this file does not support rails code, but I have written it in here so you understand what I am trying to do.

jQuery ->
  if $('.pagination').length
    $(window).scroll ->
      url = $('.pagination .next_page').attr('href')
      if url && $(window).scrollTop() > $(document).height() - $(window).height() - 1200
        $('.pagination').html("<%= image_tag("loading.gif") %> Loading more...")
        $.getScript(url)
    $(window).scroll()

Previously, I would have just written it in pure HTML, using <img src=... But this will no longer work with the asset pipeline. How can I achieve this?

like image 394
tob88 Avatar asked Jun 20 '12 17:06

tob88


1 Answers

Using plain HTML should work just fine.

Try using: <img src="/assets/loading.gif" /> if your loading.gif is inside assets/images.

UPDATED 21/06/2012

As per the Ruby on Rails Guide, Section 2.2.3, changing the file extension of your .js file to filename.js.erb or filename.js.coffee.erb will allow you to use embedded ruby inside your javascript.

You can then use the asset_path helper to access the path where your assets are stored.

like image 157
Zajn Avatar answered Sep 24 '22 18:09

Zajn