Handlebars templating and dynamic images

2019-04-06 02:30发布

问题:

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?

回答1:

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.



回答2:

I know it is late but here is how to do what you want :

var view = Ember.View.create({templateName: 'myTemplate', myPicture: 'http://url_of_my_picture.png'});

view.appendTo('#myDiv');

<script type="text/x-handlebars" data-template-name="myTemplate">
    <img {{bindAttr src="myPicture"}}>
</script>


回答3:

I found that using triple brackets will work fine.

<img src="{{{your source}}}" alt={{{your alt}}} />


回答4:

None of the answers worked for me. I got it to work by converting the image into base64 and sending that as the img src inside the handlebars template

template.hbs

{{#if img_src}}
    <img src="{{{img_src}}}" alt=""/>
{{/if}}

source.js

data = {
         img_src: base64img.base64Sync('./assets/img/test.png');
       }