a blog for those who code

Wednesday 20 July 2016

Creating Templates in Ember.js

In this post we will be discussing about creating templates in Ember.js. It uses HTMLBars which is built on top of Handlebars, thus combining HTML and Handlebars will give us HTMLBars. As you all know Handlebars is a lightweight HTML templating engine thus Ember uses it to create its templates. Ember-cli is used to compile the templates whereas data is passed in via Route.

What are Templates and how to create it

Templates are just HTML plus {{ }} for ex : <h1>{{data.value1}}</h1>. The template file has an extension of .hbs as shown below

Application template (application.hbs) is the default template that is rendered when you application starts. That means you have to put your header, footer or any other decorative content there. Basic application.hbs file looks like below

<h2 id="title">Welcome to Ember.js</h2>

{{input id="test-input" value=value}}

<div id="first-value">{{values.firstObject}}</div>
<div id="last-value">{{values.lastObject}}</div>


You can also keep your templates in HTML. To do that you have to create a <script> tag without a template name. Ember will use the template without a name as the application template and it will automatically be compiled and appended to the screen as shown below

<script type="text/x-handlebars">

Templates Features

Debugging : You can do debugging in template in the following ways

1. {{log model}} - To log your data
2. {{debugger}} - To force a debugger break

Enumerating Data : It will take the model and iterates one by one

{{#each model as |modelName|}}

Binding Element Attributes : You can bind element attributes to the controller

 <img {{bind-attr src=someUrl}} alt="Img">

Create Links : You can create link to a route using {{link-to}} helper

{{#link-to 'model.childModel' model}}Model{{/link-to}}

Adding Bootstrap to Ember

Along with the above features you acn also add bootstrap to ember using the ember-bootstrap plugin. Its an ember-cli addon for using Twitter Bootstrap in Ember Applications.

Please Like and Share the CodingDefined Blog, if you find it interesting and helpful.

No comments:

Post a Comment