将模型属性插入到Ember中的Img元素URL中 [英] Inserting a Model Property into an Img Element URL in Ember
问题描述
我有一个具有 image_id
属性的模型。我有一个包含图像元素的模型的视图。我需要将id插入到图像元素的 src
属性中以完成图像的URL,以便我有效地执行此操作:
I have a Model with an image_id
property. I have a View for that Model that contains an image element. I need to insert the id into the image element's src
property to complete the URL of the image so that I'm effectively doing this:
<img src="news + newsItem.imageID + .jpg"></img>
我第一次尝试使用Handlebars助手:
My first attempt used a Handlebars helper:
<img src="news{{newsImageURL newsItem.imageID}}.jpg"></img>
但这也插入了Metamprph脚本标签:
But this also inserted Metamprph script tags around it:
<img url="<script id='metamorph-10-start' type='text/x-placeholder'></script>news/7.jpg<script id='metamorph-10-end' type='text/x-placeholder'></script>" alt="" class="content-image news-media" /></a>
所以我看过使用 bindAttr
但是,由于我需要转换image_id值(通过预先添加并附加路径的其余部分),这似乎也不是解决方案。
So I've looked at using bindAttr
, however as I need to transform the image_id value(by prepending and appending the rest of the path), this doesn't seem like a solution either.
推荐答案
有两种可能性:
1-将模型的图像路径声明为计算属性。如果你不喜欢,你可以在你的ObjectController 中声明它也支持这个模板:
1- Declare the image path as computed property on your model. If you don't like that, you could declare it also in your ObjectController backing this template:
模板:
// until 1.0 RC7
<img {{bindAttr src="newsItem.imagePath"}}></img>
// from 1.0 final (the above one is deprecated)
<img {{bind-attr src=newsItem.imagePath}}></img>
模型:
App.NewsItem = DS.Model.extend({
imageID: DS.attr('string'),
imagePath: function() {
return "/assets/news/"+this.get("imageID")+".jpg";
}.property('imageID')
});
2-如果你不需要绑定1(我猜你的id不会改变)并使用 unbound helper
,这不会导致脚本标签:
2- If you do not need the binding in 1 (i guess your id won't change) and use the unbound helper
, which does not result in script tags:
<img src="news{{unbound newsItem.imageID}}.jpg"></img>
这篇关于将模型属性插入到Ember中的Img元素URL中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!