Binding with element attributes and classes

A very useful feature of HTMLBars is binding elements to attributes in your HTML.

How to do it...

A very simple example would be binding an element to an img src tag.

  1. In a new project, generate index template and index controller:
    $ ember g template index
    $ ember g controller index
    

    This will generate the files needed for this example.

  2. Create a new 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.

  3. Create a new template and add an 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.

  4. The template will be rendered with the url property as follows:
    <img src="http://placehold.it/350x200"/>

    We can essentially add this to any tag we like.

  5. Let's create a 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.

    Tip

    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/.

How it works...

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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset