01 Project – Node.js / Express / MongoDB – Part 09 – Creating Partials

Partials are small views that we can insert in any part of our web page. Using partials is a good practice in web development since partials reduce code duplication and create reusable components.

For our application, we’re using partials for the sidebar in the main layout. With every view’s viewModel , we will include a JavaScript object called sidebar that will contain the data specifically for the stats, popular images, and recent comments found within the sidebar partial.

Let’s create the HTML for each of the partials. Within the views/partials/ path create the following three files: stats.handlebars, popular.handlebars, and comments.handlebars. The code of each three files is presented below:

stats.handlebars file

<div class="panel panel-default">
  <div class="panel-heading">
    <h3 class="panel-title">Stats</h3>
  </div>
  <div class="panel-body">
    <div class="row">
      <div class="col-md-2 text-left">Images:</div>
      <div class="col-md-10 text-right">{{ sidebar.stats.images }}</div>
    </div>
    <div class="row">
      <div class="col-md-2 text-left">Comments:</div>
      <div class="col-md-10 text-right">{{ sidebar.stats.comments }}</div>
    </div>
    <div class="row">
      <div class="col-md-2 text-left">Views:</div>
      <div class="col-md-10 text-right">{{ sidebar.stats.views }}</div>
    </div>
    <div class="row">
      <div class="col-md-2 text-left">Likes:</div>
      <div class="col-md-10 text-right">{{ sidebar.stats.likes }}</div>
    </div>
  </div>
</div>

popular.handlebars file

<div class="panel panel-default">
  <div class="panel-heading">
    <h3 class="panel-title">Most Popular</h3>
  </div>
  <div class="panel-body">
    {{#each sidebar.popular}}
    <div class="col-md-4 text-center" style="padding-bottom: .5em;">
      <a href="/images/{{uniqueId}}"><img src="/public/upload/{{filename}}" style="width: 75px; height: 75px;" class="img-thumbnail"></a>
    </div>
    {{/each}}
  </div>
</div>

comments.handlebars file

<div class="panel panel-default">
  <div class="panel-heading">
    <h3 class="panel-title">Latest Comments</h3>
  </div>
  <div class="panel-body">
    <ul class="media-list">
      {{#each sidebar.comments}}
      <li class="media">
        <a class="pull-left" href="/images/{{image.uniqueId }}">
          <img class="media-object" width="45" height="45" src="/public/upload/{{ image.filename }}">
        </a>
        <div class="media-body">
          {{comment}}<br/>
          <strong class="media-heading">{{name}}</strong> <small class="text-muted">{{timeago timestamp }}</small>
        </div>
      </li>
      {{/each}}
    </ul>
  </div>
</div>

Leave a Reply