Adding Routes for our collection

Now that we have some posts lets create some routes.

  1. Make routes.js look like:

    client/routes.js

     Meteor.Router.add({
       '/': function () {
         return 'home';
       },
       '/posts': function (tags) {
         // Set the query to all
         Session.set('postQuery', {});
         return 'postList';
       },
       '/posts/:id': function (id) {
         // Set the session var 'postId' - we will use this value in our
         // template helper to query for the correct post.
         Session.set('postId', id);
         return 'postDetail';
       },
       '/posts/tags/:tag': function (tag) {
         // Set the query to tags matching the passed tag
         Session.set('postQuery', {tags: tag});
         return 'postList';
       }
     });
    
  2. Create the postList template:

    client/views/posts/post_list.html

      <template name="postList">
        <ul class="thumbnails">
          {{#each allPosts}}
          <li class="span2">
            <a href="/posts/{{_id}}">
              <h3>{{title}}</h3>
            </a>
            <p>{{body}}</p>
          </li>
          {{/each}}
        </ul>
      </template>
    
    

    And add the following template helpers:

    client/views/posts/post_list.js

      Template.postList.allPosts = function () {
        // return the posts matching the query set in the routes.
        return Posts.find(Session.get('postQuery'));
      };
    

    When you visit http://localhost:3000/posts you should see:

    Hello World

    Full body text will go here...

    And When you visit http://localhost:3000/posts/tags/first you should see:

    Hello World

    Full body text will go here...

  3. Create the postDetail template:

    client/views/posts/post_detail.html

      <template name="postDetail">
        <h2>{{post.title}}</h2>
        {{{post.body}}}
      </template>
    
    

    And add the following template helpers:

    client/views/posts/post_detail.js

      Template.postDetail.post = function () {
        // use the 'postId' session variable to retrieve the correct session
        // based on the url.
        return Posts.findOne({_id: Session.get('postId')});
      };
    

    When you visit http://localhost:3000/posts/:postID you should see:

    Hello World

    Full body text will go here...

Resources

  • Chrome Developer Tools: Console - The Console is accessible from any panel. Unlike the other panels, the Console is not just used for one task, instead it might be used while inspecting the DOM, debugging JavaScript or analyzing HTML parse errors.

Comments