A very useful feature of HTMLBars is binding elements to attributes in your HTML.
A very simple example would be binding an element to an img src
tag.
index template
and index controller
:$ ember g template index $ ember g controller index
This will generate the files needed for this example.
index controller
file with url
, sideClass
, and secondClass
as its properties:// app/controllers/index.js import Ember from 'ember'; export default Ember.Controller.extend({ url: 'http://placehold.it/350x200', sideClass: 'cc', secondClass: 'dd' });
We get the index
route and controller without having to create a specific route for them. It works like the application route, which all other routes inherit from.
img
tag. The url
element will be displayed:// app/templates/index.hbs <img src="{{url}}"/>
This will be rendered as if the url
property is in the src
attribute for the img
tag.
url
property as follows:<img src="http://placehold.it/350x200"/>
We can essentially add this to any tag we like.
div
tag in our template with a couple of properties added for the class:// app/templates/index.hbs <div id="side" class="{{sideClass}} {{secondClass}}">Info</div>
Both sideClass
and secondClass
will be added to the class attribute. As these properties are bound, they act like any other property in Ember. They can be dynamically changed and the template will render accordingly.
Content security policy
When running examples in this book, you might occasionally see messages in the console warning you about content security violations. They'll usually appear in big red text in your console. The Ember team put this in place to help remind developers about potential security issues that your application might have. For the purpose of this book, these warnings can be ignored. On the other hand, you can fix these warnings by editing the config/environment.js
file and the contentSecurityPolicy
section. You can find examples on how content security works at http://content-security-policy.com/.
Binding elements in attributes is done by the HTMLBars templating library, which is based on the Handlebars library. It looks at every attribute with a property and renders it on the screen. These attributes are bound to properties that can be accessed in the controller or component.
We can bind any property to any attribute. The only exception being view helpers. We'll discuss this more in a later part of the chapter.