Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Building Single-page Web Apps with Meteor
Building Single-page Web Apps with Meteor

Building Single-page Web Apps with Meteor: Build real-time single page apps at lightning speed using the most powerful full-stack JavaScript framework around

eBook
€8.99 €16.99
Paperback
€20.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Building Single-page Web Apps with Meteor

Chapter 2. Building HTML Templates

After we successfully installed Meteor and set up our folder structure, we can now start building the basic templates for our blog.

In this chapter, we will learn how templates are built. We will see how to display data and how some parts can be altered using helper functions. We will take a look on adding events, using conditions, and understanding data contexts, all in templates.

The following is an overview of what will be covered in this chapter:

  • The basic template structure
  • Displaying data
  • Writing template helper functions
  • Using conditions in templates
  • Data contexts and how those can be set
  • Nesting templates and data context inheritance
  • Adding events
  • Building block helpers

    Note

    If you jump right into this chapter without setting up the folder structure in the Chapter 1, Getting Started with Meteor, download the previous chapter's code examples from either the book's web page at https://www.packtpub.com/books/content/support/17713 or from the...

Writing templates in Meteor

Normally when we build websites, we build the complete HTML on the server side. This was quite straightforward; every page is built on the server, then it is sent to the client, and at last JavaScript added some additional animation or dynamic behavior to it.

This is not so in single-page apps, where every page needs to be already in the client's browser so that it can be shown at will. Meteor solves this problem by providing templates that exists in JavaScript and can be placed in the DOM at some point. These templates can have nested templates, allowing for an easy way to reuse and structure an app's HTML layout.

Since Meteor is so flexible in terms of folder and file structure, any *.html page can contain a template and will be parsed during Meteor's build process. This allows us to put all templates in the my-meteor-blog/client/templates folder, which we created in the Chapter 1, Getting Started with Meteor. This folder structure is chosen as...

Building the basic templates

Now, let's add the basic templates to our blog by creating a file called layout.html in the my-meteor-blog/client/templates folder. This template will serve as the wrapper template for our blog layout. To build the basic templates, perform the following steps:

  1. Add the following lines of code to layout.html, which we just created:
    <template name="layout">
      <header>
        <div class="container">
          <h1>My Meteor Single Page App</h1>
          <ul>
            <li>
              <a href="/">Home</a>
            </li>
            <li>
              <a href="/about">About</a>
            </li>
          </ul>
        </div>
      </header>
    
      <div class="container">
        <main>
        </main>
      </div>
    </template>
  2. Next, we will create the home page template, which will later list all our blogs posts. In the same templates folder...

Adding templates and partials

To show the home template in the app, we need to open index.html, which we created earlier, and perform the following steps:

  1. We replace Hello World with the following template inclusion helper:
    {{> layout}}
  2. If we go back to our browser now, we see that the text is gone and the layout template, which we created earlier, has appeared with its header and menu.
  3. To complete the page, we need to show the home template in the layout template. We do this by simply adding another template inclusion helper to the main section of the layout template in our layout.html file, as follows:
    <main>
      {{> home}}
    </main>
  4. If we go back to the browser, we should see the following screenshot:
    Adding templates and partials

If we would now switch {{> home}} for {{> about}}, we would see our about template instead.

Displaying data with template helpers

Each template can have functions, which are called template helpers, and they can be used inside the template and child templates.

In addition to our custom helper functions, there are three callback functions that are called when the template is created, rendered, and destroyed. To display data with template helpers, perform the following steps:

  1. To see the three callback functions in action, let's create a file called home.js and save it to our my-meteor-blog/client/templates/ folder with the following code snippet:
    Template.home.created = function(){
      console.log('Created the home template');
    };
    Template.home.rendered = function(){
      console.log('Rendered the home template');
    };
    
    Template.home.destroyed = function(){
      console.log('Destroyed the home template');
    };

    If we now open the console of our browser, we will see the first two callbacks are being fired. The last one will only fire if we dynamically remove the...

Setting the data context for a template

Now that we've seen how we can display data using a helper, let's see how we can set the whole data context of a template:

  1. For the next examples, we will create a file called examples.html in our my-meteor-blog/client/templates folder and add the following code snippet:
    <template name="contextExample">
      <p>{{someText}}</p>
    </template>
  2. Now that we have our contextExample template, we can add it to our home template by passing some data as follows:
    {{> contextExample someText="I was set in the parent template's helper, as an argument."}}

    This will show the text in the contextExample template because we were displaying it using {{someText}}.

    Tip

    Remember that filenames don't really matter as Meteor is collecting and concatenating them anyway; however, the template name matters since we use this to reference templates.

    Setting the context in HTML is not very dynamic, as it is hardcoded. To be...

Writing templates in Meteor


Normally when we build websites, we build the complete HTML on the server side. This was quite straightforward; every page is built on the server, then it is sent to the client, and at last JavaScript added some additional animation or dynamic behavior to it.

This is not so in single-page apps, where every page needs to be already in the client's browser so that it can be shown at will. Meteor solves this problem by providing templates that exists in JavaScript and can be placed in the DOM at some point. These templates can have nested templates, allowing for an easy way to reuse and structure an app's HTML layout.

Since Meteor is so flexible in terms of folder and file structure, any *.html page can contain a template and will be parsed during Meteor's build process. This allows us to put all templates in the my-meteor-blog/client/templates folder, which we created in the Chapter 1, Getting Started with Meteor. This folder structure is chosen as it helps us organizing...

Building the basic templates


Now, let's add the basic templates to our blog by creating a file called layout.html in the my-meteor-blog/client/templates folder. This template will serve as the wrapper template for our blog layout. To build the basic templates, perform the following steps:

  1. Add the following lines of code to layout.html, which we just created:

    <template name="layout">
      <header>
        <div class="container">
          <h1>My Meteor Single Page App</h1>
          <ul>
            <li>
              <a href="/">Home</a>
            </li>
            <li>
              <a href="/about">About</a>
            </li>
          </ul>
        </div>
      </header>
    
      <div class="container">
        <main>
        </main>
      </div>
    </template>
  2. Next, we will create the home page template, which will later list all our blogs posts. In the same templates folder as layout.html, we will create a file named home.html...

Adding templates and partials


To show the home template in the app, we need to open index.html, which we created earlier, and perform the following steps:

  1. We replace Hello World with the following template inclusion helper:

    {{> layout}}
  2. If we go back to our browser now, we see that the text is gone and the layout template, which we created earlier, has appeared with its header and menu.

  3. To complete the page, we need to show the home template in the layout template. We do this by simply adding another template inclusion helper to the main section of the layout template in our layout.html file, as follows:

    <main>
      {{> home}}
    </main>
  4. If we go back to the browser, we should see the following screenshot:

If we would now switch {{> home}} for {{> about}}, we would see our about template instead.

Displaying data with template helpers


Each template can have functions, which are called template helpers, and they can be used inside the template and child templates.

In addition to our custom helper functions, there are three callback functions that are called when the template is created, rendered, and destroyed. To display data with template helpers, perform the following steps:

  1. To see the three callback functions in action, let's create a file called home.js and save it to our my-meteor-blog/client/templates/ folder with the following code snippet:

    Template.home.created = function(){
      console.log('Created the home template');
    };
    Template.home.rendered = function(){
      console.log('Rendered the home template');
    };
    
    Template.home.destroyed = function(){
      console.log('Destroyed the home template');
    };

    If we now open the console of our browser, we will see the first two callbacks are being fired. The last one will only fire if we dynamically remove the template.

  2. To display data in the home...

Setting the data context for a template


Now that we've seen how we can display data using a helper, let's see how we can set the whole data context of a template:

  1. For the next examples, we will create a file called examples.html in our my-meteor-blog/client/templates folder and add the following code snippet:

    <template name="contextExample">
      <p>{{someText}}</p>
    </template>
  2. Now that we have our contextExample template, we can add it to our home template by passing some data as follows:

    {{> contextExample someText="I was set in the parent template's helper, as an argument."}}

    This will show the text in the contextExample template because we were displaying it using {{someText}}.

    Tip

    Remember that filenames don't really matter as Meteor is collecting and concatenating them anyway; however, the template name matters since we use this to reference templates.

    Setting the context in HTML is not very dynamic, as it is hardcoded. To be able to dynamically change the context,...

"this" in template helpers and template callbacks


In Meteor, this in template helpers is used differently in template callbacks such as created(), rendered(), and destroyed().

As already mentioned, templates have three callback functions that are fired in different states of the template:

  • created: This fires when the template gets initiated but is not yet in the DOM

  • rendered: This fires when the template and all its sub templates are attached to the DOM

  • destroyed: This fires when the template is removed from the DOM and before the instance of the template gets destroyed

In these callback functions, this refers to the current template instance. The instance object can access the templates DOM and comes with the following methods:

  • this.$(selectorString): This method finds all elements that match selectorString and returns a jQuery object from those elements.

  • this.findAll(selectorString): This method finds all elements that match selectorString, but returns the plain DOM elements.

  • this.find(selectorString...

Left arrow icon Right arrow icon

Description

If you are a web developer with basic knowledge of JavaScript and want to take on Web 2.0, build real-time applications, or simply want to write a complete application using only JavaScript and HTML/CSS, this is the book for you. This book is based on Meteor 1.0.

Who is this book for?

If you are a web developer with basic knowledge of JavaScript and want to take on Web 2.0, build real-time applications, or simply want to write a complete application using only JavaScript and HTML/CSS, this is the book for you.

What you will learn

  • Create reactive templates that update themselves when data changes
  • Use database queries on the client and the server to retrieve, sort, and manipulate datasets
  • Understand data synchronization using a publication/subscription model and make API calls a thing of the past
  • Discover how you can secure your data flow on the server side to keep confidential data secret
  • Add routing to a singlepage application and make it appear like a real website
  • Build your own advanced reactive objects and make everything rerun when you want
  • Make your own Meteor packages and learn how to make them public
  • Unit test your packages and Meteor applications

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jan 27, 2015
Length: 198 pages
Edition : 1st
Language : English
ISBN-13 : 9781783988136
Vendor :
Meteor Development Group
Languages :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Jan 27, 2015
Length: 198 pages
Edition : 1st
Language : English
ISBN-13 : 9781783988136
Vendor :
Meteor Development Group
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 75.97
Meteor Cookbook
€32.99
Building Single-page Web Apps with Meteor
€20.99
Getting Started with Meteor.js JavaScript Framework - Second Edition
€21.99
Total 75.97 Stars icon
Banner background image

Table of Contents

14 Chapters
1. Getting Started with Meteor Chevron down icon Chevron up icon
2. Building HTML Templates Chevron down icon Chevron up icon
3. Storing Data and Handling Collections Chevron down icon Chevron up icon
4. Controlling the Data Flow Chevron down icon Chevron up icon
5. Making Our App Versatile with Routing Chevron down icon Chevron up icon
6. Keeping States with Sessions Chevron down icon Chevron up icon
7. Users and Permissions Chevron down icon Chevron up icon
8. Security with the Allow and Deny Rules Chevron down icon Chevron up icon
9. Advanced Reactivity Chevron down icon Chevron up icon
10. Deploying Our App Chevron down icon Chevron up icon
11. Building Our Own Package Chevron down icon Chevron up icon
12. Testing in Meteor Chevron down icon Chevron up icon
A. Appendix Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.5
(8 Ratings)
5 star 62.5%
4 star 25%
3 star 12.5%
2 star 0%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Ian Sep 04, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
very good intro to meteor. if you know nodejs, you can start building simple apps with meteor now. with this book, you will not be able to write a facebook, but you can gain a lot of foundamental 'ideas'.the author does have a follow-up tutorial series on the internet, which further extends your understanding of meteor. after that, plus if you know bootstrap, you will then be able to build some interesting stuff.highly recommend!
Amazon Verified review Amazon
Sam Hagman Mar 24, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This is a great book for "amateur beginners" and "advanced beginners" alike.What I mean "amateur beginners" are programmers that know some JavaScript and have seen and played around with Node. "Advanced beginners" are programmers that already know a JavaScript framework on the front-end and also a Node framework on the back-end and have had a lot of experience with JavaScript.For the "amateur beginners" you get a book that explains things in simple, clear terms and has just enough depth of explanation that you can understand why Meteor is so cool. For "advanced beginners" you get a great discussion of the different options for some trickier aspects of Meteor like deployment and under-the-hood Meteor reactivity.I have read several Meteor books and lots and lots of articles about Meteor and I feel that this book gives a great overview of the Meteor platform. I think my favorite part of the book is that it acknowledges where things have more depth than what can fit in the book, which gave me a bunch of direction on where to focus my Google searches to understand Meteor on a more advanced level.Overall, great book if you want to learn Meteor from scratch.
Amazon Verified review Amazon
Paul Mar 18, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I would recommend this to anyone looking for a gentle easy to follow introduction to Meteor. It pretty much does what other books do by leading you through how to create a blog (accounts, permissions, routing etc).The sections on packaging and deployment are clear to understand.Chapter 12 on testing with Velocity is well worth the money spent on the book. This is a great new feature of Meteor which is explained well in the book.It is up to date with the latest version of Meteor.
Amazon Verified review Amazon
Bharat C. Ruparel May 17, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I am working through the book line-by-line and approximate half-way through the book (Chapter 6). I do not want to wait anymore to write this review since this book may be just what you need if you have any interest in learning meteor. Fabian writes in a very clear and simple style and obviously knows Meteor well.My main motivation in writing the review here is two-fold:1. I read reviews before purchasing any books or materials and more often than not, have benefitted from them. So I want to return the favor by giving an enthusiastic thumbs-up for anyone wanting to learn Meteor.2. I am hoping that Fabian follows up this excellent effort by a more intermediate/advanced text where he addresses the issues that a developer has to tackle in creating real-life production applications. While this book does its job very well in explaining the basics using a running blog example, the same style could be used to write a more advanced text that deals with real-life issues. Almost always that involves using third-party packages, so a demonstration of how to use them in the context of an application would be very useful.I am an experienced Rails developer and am looking to Meteor to make my applications more responsive (or shall we say reactive?) leading to a better user experience. Also, another obvious benefit is the scalability since clients can do more computations and far more important, rendering of pages. As Javascript runtimes in the browsers (also in the servers, e.g. node.js) improve rapidly, it makes no sense to do most of the page rendering on the server. It should be the client.I have gone through other texts on Meteor as well as the official tutorial. This book by far, is the clearest. Fabian, Keep up the great work and follow through on my suggestion :) I will buy a book written by you anytime if the topic is of interest to me as it is here.
Amazon Verified review Amazon
Asit Dhal Jan 05, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book is my first exposure towards Meteor. This book gives excellent beginning towards Meteor.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.