Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handlebars templating and dynamic images

In my templates I am doing something like

<img class="someClass" src="{{imgURL}}">

The images are loaded correctly but I get warnings like:

GET http://localhost:8888/%7B%imgURL%7D%7D 404 (Not Found)

Is there a way to fix this?

like image 679
swallace Avatar asked Sep 21 '12 13:09

swallace


People also ask

What is handlebars template?

What is Handlebars? Handlebars is a simple templating language. It uses a template and an input object to generate HTML or other text formats. Handlebars templates look like regular text with embedded Handlebars expressions.

Is handlebars a template engine?

Handlebars: What it is and Why to Use itHandlebars is a logic-less templating engine that dynamically generates your HTML page.

What is handlebars template in Ember?

Ember uses the Handlebars templating library to power your app's user interface. Handlebars templates contain static HTML and dynamic content inside Handlebars expressions, which are invoked with double curly braces: {{}} . Dynamic content inside a Handlebars expression is rendered with data-binding.

What is the difference between EJS and handlebars?

EJS is way faster than Jade and handlebars. EJS has a really smart error handling mechanism built right into it. It points out to you, the line numbers on which an error has occurred so that you don't end up looking through the whole template file wasting your time in searching for bugs.


1 Answers

You have two problems:

  1. You're missing a closing quote in your <img> but that's not a big deal.
  2. Your template is being stored in a hidden <div> or similar element that contains HTML.

If you say this:

<div id="t" style="display: none">
    <img class="someClass" src="{{imgURL}}">
</div>

the browser will interpret the <img> as a real image and try to load the resource specified in the src attribute, that's where your 404:

GET http://localhost:8888/%7B%imgURL%7D%7D 404 (Not Found)

comes from. Templates are rarely valid and properly formed HTML so you need to keep the browser from trying to interpret template as HTML. The usual approach is to store the template in a <script> with a non-HTML type:

<script id="t" type="text/x-handlebars-template">
    <img class="someClass" src="{{imgURL}}">
</script>

Then you can say Handlebars.compile($('#t').html()) to get your compiled template and the browser won't try to interpret the #t content as HTML.

like image 96
mu is too short Avatar answered Sep 24 '22 05:09

mu is too short