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

Arrow left icon
Profile Icon Fabian Vogelsteller
Arrow right icon
AU$24.99 per month
Full star icon Full star icon Full star icon Full star icon Half star icon 4.5 (8 Ratings)
Paperback Jan 2015 198 pages 1st Edition
eBook
AU$14.99 AU$29.99
Paperback
AU$37.99
Subscription
Free Trial
Renews at AU$24.99p/m
Arrow left icon
Profile Icon Fabian Vogelsteller
Arrow right icon
AU$24.99 per month
Full star icon Full star icon Full star icon Full star icon Half star icon 4.5 (8 Ratings)
Paperback Jan 2015 198 pages 1st Edition
eBook
AU$14.99 AU$29.99
Paperback
AU$37.99
Subscription
Free Trial
Renews at AU$24.99p/m
eBook
AU$14.99 AU$29.99
Paperback
AU$37.99
Subscription
Free Trial
Renews at AU$24.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $24.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
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 : 9781783988129
Vendor :
Meteor Development Group
Languages :
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. $24.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

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

Packt Subscriptions

See our plans and pricing
Modal Close icon
AU$24.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
AU$249.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 AU$5 each
Feature tick icon Exclusive print discounts
AU$349.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 AU$5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total AU$ 138.97
Meteor Cookbook
AU$60.99
Building Single-page Web Apps with Meteor
AU$37.99
Getting Started with Meteor.js JavaScript Framework - Second Edition
AU$39.99
Total AU$ 138.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

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.