跳转到: 导航搜索


Meteor Tutorials

在这个例子里,main.html与main.js中调用的{{> hi}}、<template name="hi">和Template.hi要一一对应。


  <h1>Welcome to Meteor!</h1>
  {{> hi}}
  {{> info}}
<template name="hi">
  <button>Please Click Me Softly</button>
  <h4>You've pressed the button {{counter}} times.</h4>
<template name="info">
  <h2>Learn Meteor!</h2>
    <li><a href="" target="_blank">Do the Tutorial</a></li>
    <li><a href="" target="_blank">Follow the Guide</a></li>
    <li><a href="" target="_blank">Read the Docs</a></li>
    <li><a href="" target="_blank">Discussions</a></li>

main.js 文件如下:

// main.js
import { Template } from 'meteor/templating';
import { ReactiveVar } from 'meteor/reactive-var';
import './main.html';
Template.hi.onCreated(function helloOnCreated() {
  // counter starts at 0
  this.counter = new ReactiveVar(0);
  counter() {
    return Template.instance().counter.get();
  'click button'(event, instance) {
    // increment the counter when button is clicked
    instance.counter.set(instance.counter.get() + 1);


HTML files in Meteor define templates

Meteor parses HTML files and identifies three top-level tags: <head>, <body>, and <template>. Everything inside any <head> tags is added to the head section of the HTML sent to the client, and everything inside <body> tags is added to the body section, just like in a regular HTML file. Everything inside <template> tags is compiled into Meteor templates, which can be included inside HTML with {{> templateName}} or referenced in your JavaScript with Template.templateName. Also, the body section can be referenced in your JavaScript with Template.body. Think of it as a special "parent" template, that can include the other child templates.

Adding logic and data to templates

All of the code in your HTML files is compiled with Meteor's Spacebars compiler. Spacebars uses statements surrounded by double curly braces such as {{#each}} and {{#if}} to let you add logic and data to your views. You can pass data into templates from your JavaScript code by defining helpers. In the code above, we defined a helper called tasks on Template.body that returns an array. Inside the body tag of the HTML, we can use {{#each tasks}} to iterate over the array and insert a task template for each value. Inside the #each block, we can display the text property of each array item using Template:Text. In the next step, we will see how we can use helpers to make our templates display dynamic data from a database collection.

 {{#each tasks}}
    {{> task}}