简体   繁体   English

把手模板和动态图像

[英]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? 有没有办法解决这个问题?

You have two problems: 您有两个问题:

  1. You're missing a closing quote in your <img> but that's not a big deal. 您在<img>缺少结束语,但这没什么大不了的。
  2. Your template is being stored in a hidden <div> or similar element that contains HTML. 您的模板存储在隐藏的<div>或包含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: 浏览器会将<img>解释为真实图像,并尝试加载src属性中指定的资源,这就是您的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. 模板很少是有效且格式正确的HTML,因此您需要避免浏览器尝试将模板解释为HTML。 The usual approach is to store the template in a <script> with a non-HTML type : 通常的方法是将模板存储在非HTML type<script>

<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. 然后,您可以说Handlebars.compile($('#t').html())来获取已编译的模板,浏览器将不会尝试将#t内容解释为HTML。

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>

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 我通过将图像转换为base64并将其作为img src发送到车把模板中来使其工作

template.hbs template.hbs

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

source.js source.js

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

我发现使用三括号可以很好地工作。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM