Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

style attribute with emberjs

Tags:

ember.js

Is there a way to set css properties by using emberjs properties' auto binding ?

Something like:

<div {{bindAttr style="background-color: divColor;"}}>
    ...
</div>
like image 429
Maël Nison Avatar asked Feb 23 '12 00:02

Maël Nison


1 Answers

Please note that as of ember 1.13. binding attributes (bind-attr) is deprecated. You would need to use code similar to this to bind to the class:

<div class={{myClass}}></div>

Furthermore, style binding in this fashion is not recommended because it can introduce XSS vulnerabilities. The HTML templating automatically escapes HTML to prevent XSS when using {{...}}, but style attributes have additional vulnerabilities outside of the scope of the built-in escaping.

The recommended approach is to escape the CSS yourself (i.e. creating the escapeCSS function that would escape the specific CSS appropriately to prevent XSS - this is not a built-in function. You could start with Ember.Handlebars.Utils.escapeExpression and add any additional checking from that base.) More information can be found here: https://guides.emberjs.com/v2.2.0/templates/writing-helpers/#toc_escaping-html-content

Then you tell Ember that the string is "safe" by using Ember.String.htmlSafe, and Ember will not try to escape that content.

controller:

myStyle: Ember.computed('color', function() {
    var color = escapeCSS(this.get('color'));
    return new Ember.String.htmlSafe("color: " + color);
  })

template:

<div style={{myStyle}}></div>

Reference: http://emberjs.com/deprecations/v1.x/#toc_binding-style-attributes

like image 157
QuantumLicht Avatar answered Oct 12 '22 13:10

QuantumLicht