Javascript 车把模板和动态图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12531743/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 10:38:24  来源:igfitidea点击:

Handlebars templating and dynamic images

javascripttemplateshandlebars.js

提问by swallace

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?

有没有办法来解决这个问题?

回答by mu is too short

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.
  1. 你错过了一个结束语,<img>但这没什么大不了的。
  2. 您的模板存储在<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 srcattribute, 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. The usual approach is to store the template in a <script>with a non-HTML type:

来自。模板很少是有效且格式正确的 HTML,因此您需要防止浏览器尝试将模板解释为 HTML。通常的方法是将模板存储在<script>带有非 HTML 的 a 中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 #tcontent as HTML.

然后你可以说Handlebars.compile($('#t').html())得到你编译的模板,浏览器不会尝试将#t内容解释为 HTML。

回答by Benjamin L.

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>

回答by Sashi

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

模板.hbs

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

source.js

源.js

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

回答by Kyriediculous

I found that using triple brackets will work fine.

我发现使用三重括号可以正常工作。

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