EmberJS- Adding Layouts to Views



Adding Layouts to Views

The layout templates are the Hhandlebars template which are used inside the view tag by setting the layoutName property. The {{yield}} helper determine where to insert the main template by informing the layout template.

   Ember.View.extend({
      layoutName: 'LayoutName',
      templateName: 'TemplateName'
   });

In the above code, define the LayoutName and TemplateName which you want to render.

Example

<!DOCTYPE html>
<html>
   <head>
      <title>Emberjs Adding Layouts to Views</title>
      <!-- CDN's-->
      <script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/3.0.1/handlebars.min.js"></script>
      <script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/ember.js/1.10.0/ember.min.js"></script>
      <script src="https://builds.emberjs.com/tags/v1.10.0-beta.3/ember-template-compiler.js"></script>
      <script src="https://builds.emberjs.com/release/ember.debug.js"></script>
      <script src="https://builds.emberjs.com/beta/ember-data.js"></script>
   </head>
   <body>
      <script type="text/x-handlebars">
         <!-- specifying the view name -->
         {{view "haslayout"}}
      </script>

      <script type="text/x-handlebars" data-template-name="mylayout">
         <!-- rendered template will be inserted in the {{yield}} helper -->
         <h1>
            Hello.. {{yield}}
         </h1>
      </script>

      <script type="text/x-handlebars" data-template-name="haslayout">
         <!-- displaying the value of name variable -->
         {{view.name}}
      </script>

      <script type="text/javascript">
         App = Ember.Application.create();

         App.HaslayoutView = Ember.View.extend({
            //defining the view here
            name: 'Mack',
            //define the layout name 'mylayout'
            layoutName: 'mylayout',
            //defining the template name as 'haslayout'
            templateName: 'haslayout'
         });
      </script>
   </body>
</html>

Output

Let's carry out the following steps to see how above code works −

  • Save above code in view_layout.htm file

  • Open this HTML file in a browser.

Advertisements