Binding style attributes warning in Ember

03 February 2016

One warning Ember might print in your console concerns binding a property to the style attribute of a DOM element, like this:

1<div class="progress-bar" style="{{barWidth}}">...</div>
1export default Ember.Controller.extend({
2  progress: 0,
3  barWidth: Ember.computed('progress', {
4    return 'width:' + this.get('progress') + '%';
5  });
6});

Handlebars escapes all html content put in double curlies but it does not do that with CSS, and thus the above makes possible a cross-site scripting attack. That is the reason for the warning and the fix for that is to convert the property (in the above case, barWidth) to a SafeString, which tells Ember that the content is safe to display. You should only do that after you have verified that the content you mark as safe cannot be injected by a malicious user. The guide describes how to do that:

1export default Ember.Controller.extend({
2  progress: 0,
3  barWidth: Ember.computed('progress', {
4    return new Ember.Handlebars.SafeString('width:' + this.get('progress') + '%');
5  });
6});

(Alternatively, you can call Ember.String.htmlSafe with the string you want to mark as safe, to the same effect.)

When I did this conversion in a recent project, though, the warning persisted. After spending a substantial amount of time pouring over the docs and even stepping through the warning stacktrace, I still could not find out what was wrong. What helped (as so many times already) was a good night sleep and taking another look at it in the morning.

Marking the string as safe was done correctly, but when binding it to the style attribute, I used double quotes around it, probably inhibiting Ember from seeing it as a SafeString:

1<div class="progress-bar" style="{{barWidth}}">...</div>

So all I had to do to make the warning go away was to remove the quotes:

1<div class="progress-bar" style={{barWidth}}>...</div>

I hope this saves you some time if you come across a similar situation in your work.

Share on Twitter