Rails image_tag with Mustache template

Recently I have been working on one rails project, In which I have used Mustache.js.

Mustache is a logic-less template which is used for client side dynamic template rendering.

You can check this link Mustache for more details.

As I’m rails developer it’s common to use image_tag for displaying images in rails, so I preferred to use image_tag for displaying images.

So when I was trying to use image_tag with mustache, I was surprised!! Why? Because, that image_tag was not working as expected. So I thought something is wrong with image_tag. And then I read more details about image_tag.

See below code…(In which image_tag was not working)


template = $("#sample_template").html()
$(“.append-here”).append(Mustache.render(template, { image_name: “Image name here”, logo: “image.jpg” }))


script#sample_template type="text/html"
  = image_tag("{{logo}}", alt: "{{image_name}}")

After using above code I got compiled version of image_tag as below.

img src="/images/image.jpg" alt="image.jpg"

Then I realized that image_tag is compiled at server side & then it sends compiled(html tag) to the client side. But mustache template is compiled at client side. So the image_tag is not working here because it’s got compiled before Mustache sends the data(image) to it.

So to resolve this issue firstly I replaced image_tag with img (html tag) and then I found asset path of the image(see in sample.html.slim below).

Then I passed the image assets path(precompiled image path) to this img tag from the Mustache template, and worked for me.

See below working code…


script#sample_template type="text/html"
     img src="{{logo}}" alt="{{image_name}}"
  var image = "#{asset_path('image.png')}"       // get assets path


template = $("#sample_template").html()
$(“.append-here”).append(Mustache.render(template, { image_name: "Image name here", logo: image }))

I know it is a very common issue which lot of people already know, but I wasted my 2-3 hours to resolve this. So I feel it might be helpful for someone.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s