问题
Using:
- ember: v1.0.0-pre.4
- ember-data: revision 11
- handlebars: 1.0.rc2
So I have a template that I've hooked up to a controller that's receiving info from an REST API. In just print out text, this is fine but these handlebar expression...
<img src="{{ imageUrl }}"/>
...when inserted into the dom look like:
<img src="<script id='metamorph-28-start' type='text/x-placeholder'></script>http://asdf.com/image.jpg<script id='metamorph-28-end' type='text/x-placeholder'></script>">
I'm obviously very new to Ember.js and Handlebars.
I've tried doing searches for "rendering urls in ember templates" and "print out html in ember mustache templates." Ack, probably obvious but I'm missing it.
回答1:
try this:
<img {{bind-attr src="imageUrl"}} />
but you can have more than just one attribute like:
<img {{bind-attr src="imageUrl" alt="imageTitle"}}>
here is the doc: http://emberjs.com/api/classes/Ember.Handlebars.helpers.html#method_bind-attr
also, can be useful in some cases where you don't need the variable to be bound, you could use:
<img src="{{unbound imageUrl}}" />
ref to the doc: http://emberjs.com/api/classes/Ember.Handlebars.helpers.html#method_unbound
but the first method is usually the best.
回答2:
Taking this a little bit further to get your feet even more wet, we can actually create a view that represents an image, and use that to add more functionality.
For instance, in the following JSFiddle I've set the view's tagName
to img
(where its default is a div
), and then added an attributeBindings
to bind attributes to the view. In our case we want to bind to the src
attribute. All we then need to do is specify the src
attribute as a property of the view, and give it a default value -- in this example, Google.
Therefore the view works as expected: we've displayed an image as part of a view.
However, taking it one step further, we can now easily change the image's src
attribute by using the .set()
method. On the magical click
event, which is invoked when the user clicks on the view in the DOM (try it yourself by clicking on Google's logo in the JSFiddle!), the src
attribute is changed from Google's logo to Yahoo's logo. Since we're observing the src
attribute from attributeBindings
, this is updated as soon as we call:
this.set('src', 'http://l.yimg.com/dh/ap/default/120910/yahoo_logo_br.png');
Full view code in case JSFiddle disappears:
App.ImageView = Ember.View.extend({
tagName: 'img',
attributeBindings: ['src'],
src: 'https://www.google.com/images/srpr/logo3w.png',
click: function() {
this.set('src', 'http://l.yimg.com/dh/ap/default/120910/yahoo_logo_br.png');
}
});
来源:https://stackoverflow.com/questions/14590314/in-ember-js-templates-how-does-one-print-out-models-property-that-will-be-use