Firebase firestore in the forum application #16: Use express handlebar and Create partials code

in #utopian-io5 years ago

Repository

https://github.com/firebase

What Will I Learn?

  • Use express handlebar
  • Create partials code

Requirements

  • Basic Javascript
  • Install Firebase

Resources

Difficulty

Basic

Tutorial Content

This tutorial will continue the next tutorial series from the tutorial series on forum applications with firebase. We have done many things in this tutorial series. So for those of you who just followed this tutorial, I suggest you follow the previous tutorial series. The application that we have created has a forum system feature and comments system. This is a tutorial series that will continue the comment system. I will refactor the codes that we previously made.

Use express handlebar

In the following tutorial, I will refactor the code that we have used during this tutorial, here we will learn how to use handlebars to create a partial script on the application that we have created. For those of you who just followed this tutorial, I suggest you follow the previous tutorial in the curriculum section.

  • Install express handlebar

Here I will use the express on the handlebar. We use the handlebar on the back end cloud function. We will use this function in the backend so we have to install express first in the functions folder. For more details we can see in the picture below:

Screenshot_3.png

We can install the express handlebar this way: npm install express-handlebars --save. We can see in the picture above we have to install the express handlebar, then we can follow the next steps.

  • How to use express handlebars

At the top, we have installed the express handlebar. now we can use it on our forum application. To use it we can require it in functions/index.js.

const hbs = require('express-handlebars');

So our goal is to use the express handlebar so that we can configure it to set the partial code that we can use in all parts of the template on the application so that we don't write the same code repeatedly. Here we will do a little configuration so that we can use partial on the templates that we have made. for more details, we can see the code below:

functions/index.js

const functions = require('firebase-functions');
const express = require('express');
const hbs = require('express-handlebars');
const cons = require('consolidate');


// Require firebase-admin
const admin = require('firebase-admin');

var serviceAccount = require("./private-key.json");

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: "https://forum-firebase-b3205.firebaseio.com"
});

const firestore = admin.firestore();

// Add this magical line of code:
firestore.settings({ timestampsInSnapshots: true });
// end setting

const db = admin.firestore();
const app = express();

// Prev tutorials
// app.engine('hbs', cons.handlebars);

//USE NEW TUTORIAL PART 16
app.engine('hbs', hbs({
    extname: 'hbs',
    partialsDir: __dirname + '/views/partials'
}));

app.set('view engine', 'hbs');
app.set('views', './views');

We can see in the code above we make changes in this tutorial. we will do a little configuration, we can set the configuration on the hbs()function. The configuration that we make we will pass into a parameter in this function in the form of a object {}.

extname: 'hbs',: extname is the extension we will use in this tutorial we will use the extension hbs.

partialsDir: __dirname + '/views/partials': Here we will set the partial file directory that we will use, here I specify the directory that I will use is in views/partials. later the partial file that we will use will be saved in this folder.

Screenshot_4.png

In this partials folder we will put all the partial code templates that we will use.

  • Create partials auth

Well, we have created the partials folder, let's make the first partial component, the auth component, so here I will make the auth component interface into one part that can be used in another template. I will use the auth component in the home.hbs template. But before I will make partial auth components first. such as the following:

partials/auth.hbs

<p class="lead">
   <button class="btn btn-danger" type="button" name="button" onclick="login('gmail')">Login Gmail</button>
   <button class="btn btn-primary" type="button" name="button" onclick="login('fb')">Login FB</button>
   <button class="btn btn-info" type="button" name="button" onclick="login('twitter')">Login Twitter</button>
   <button class="btn btn-success" type="button" name="button" onclick="logout()">Log out</button>
</p>

The HTML code above is the interface of auth that we use in the application. To use this template we can use it in this way:

home.hbs

<h1 class="display-4">Hi, Welcome to forum app in firebase!</h1>
  <p class="lead">This is a simple hero unit, a simple jumbotron-style component for calling extra attention to featured content or information.</p>
  <hr class="my-4">
  <p>It uses utility classes for typography and spacing to space content out within the larger container.</p>
  (html comment removed:   previous tutorial
  <p class="lead">
   <button class="btn btn-danger" type="button" name="button" onclick="login('gmail')">Login Gmail</button>
   <button class="btn btn-primary" type="button" name="button" onclick="login('fb')">Login FB</button>
   <button class="btn btn-info" type="button" name="button" onclick="login('twitter')">Login Twitter</button>
   <button class="btn btn-success" type="button" name="button" onclick="logout()">Log out</button>
  </p> end  )
    
    (html comment removed:  new added)
  {{> auth}}
  <hr>

We can see the difference in the code above. we can use the auth component in this way {{> auth}}. auth is the name of the component in the partials folder.

If there is no error then we can see the results as follows:

ezgif.com-video-to-gif (2).gif

Now we have a partial auth component in our firebase forum application. Now we can use it in the template we want.

  • Create partials script

Please note that not only HTML elements can we use for partials of code but we can also use partials code for javascript. here we use a lot of import javascript in every template we make. we will learn how to make partials of code for javascript so we can minimize javascript code. For more details, we can see the sample code below:

Screenshot_5.png

We can see in the picture above we have the same javascript code in a different template. We will try to move it into a javasciript partial code so that we can use it repeatedly. I will create a new partials called scripts.hbs. For more details, we can see examples like the following:

views/partials/scripts.hbs

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://www.gstatic.com/firebasejs/4.11.0/firebase.js"></script>
<script type="text/javascript" src="https://www.gstatic.com/firebasejs/6.0.2/firebase-firestore.js"></script>
<script type="text/javascript">
    // Your web app's Firebase configuration
  var firebaseConfig = {
    apiKey: "AIzaSyBjqtIMpcWqEVA1SsI5lkDhDPQZHvdaKYM",
    authDomain: "forum-firebase-b3205.firebaseapp.com",
    databaseURL: "https://forum-firebase-b3205.firebaseio.com",
    projectId: "forum-firebase-b3205",
    storageBucket: "forum-firebase-b3205.appspot.com",
    messagingSenderId: "831909117594",
    appId: "1:831909117594:web:05602291ce42908b"
  };
    // Initialize Firebase
      firebase.initializeApp(firebaseConfig);
</script>

Screenshot_6.png
Here I will load the javascript and CSS file that we are using, Now to load it in the template that will use it, here I will use the partial code in the template home.hbs.

home.hbs

<!DOCTYPE html>
<html>
<head>
    <title>This the homepage</title>
    {{> scripts}}
</head>
<body>
<div class="jumbotron">
  <h1 class="display-4">Hi, Welcome to forum app in firebase!</h1>
  <p class="lead">This is a simple hero unit, a simple jumbotron-style component for calling extra attention to featured content or information.</p>
  <hr class="my-4">
  <p>It uses utility classes for typography and spacing to space content out within the larger container.</p>
  {{> auth}}
  <hr>
<h2>List of Forums</h2>
<ul>
    {{#each dataForums}}
    <li><a href="/forum/{{slug}}">{{title}}</a></li>
    <span style="display:block;"><i><b>Desc :</b></i> {{desc}}</span>
    {{/each}}
</ul>
<h2>Add Forum</h2>
  <form>
    <div class="form-group">
        <label for="title">Title</label>
        <input type="text" class="form-control" id="title" placeholder="Your tittle">
    </div>
    <div class="form-group">
        <label for="desc">Desciptions</label>
        <textarea class="form-control" id="desc" rows="3"></textarea>
    </div>
    <button class="btn btn-info" type="button" name="button" onclick="addTopic()">Add topic</button>
  </form>
</div>
<script type="text/javascript" src="/assets/js/auth.js"></script>
</body>
</html>

We can see in the code above, our home.hbs the template is lighter and shorter. we can use the partial code like this {{> scripts}}. We can also use it on other templates such as forum-details.hbs.

forum-details.hbs

<!DOCTYPE html>
<html>
<head>
    <title>This the homepage</title>
    {{> scripts}}
</head>
<body>
<div class="jumbotron">
    <h1 class="display-4">Hi, This the single forum. you can see any detail!</h1>
    <hr class="my-4">
    <p>It uses utility classes for typography and spacing to space content out within the larger container.</p>
    {{> auth}}
    <hr>
    <h2>Forum {{forum.title}}</h2>
    <p>{{forum.desc}} <span><i>by: <b>{{forum.user.username}}</b></i></span></p>
    <input type="hidden" name="owner_uid" id="owner_id" value="{{forum.user.user_id}}">
    <input type="hidden" name="forum_id" id="forum_id" value="{{forum.id}}">
    <a href="#" class="btn btn-info is-hidden" id="btn-edit" onclick="showEditForm()">Edit</a>
</div>

Well, we have replaced all templates using partial code now we will see if there is an error or not, we can see the results as shown below:

ezgif.com-video-to-gif.gif

Well we can see we managed to create a partial code on the application that we have created, so we have successfully refactored the code using the express-handle bar that we installed at the beginning, just get here my tutorial. Hopefully, it will be useful for you.

Curriculum

  • Forum app

Firebase app#1, Firebase app#2, Firebase app#3, Firebase app#4, Firebase app#5, Firebase app#6, Firebase app#7, Firebase app#8, Firebase app#9, Firebase app#10,

Proof of work done

https://github.com/milleaduski/firebase-forum

Sort:  

Thank you for your contribution @duski.harahap.
After reviewing your contribution, we suggest you following points:

  • You improved the structure of your tutorial. Good job!

  • Using the first person in the tutorials makes it difficult to understand the tutorials. We suggest using the third person in your text.

  • The GIF at the end of your tutorial is very enlightening for the reader to understand what was explained in the contribution.

  • Thanks for following some of our suggestions in your previous tutorials.

Thank you for your work in developing this tutorial.
Looking forward to your upcoming tutorials.

Your contribution has been evaluated according to Utopian policies and guidelines, as well as a predefined set of questions pertaining to the category.

To view those questions and the relevant answers related to your post, click here.


Need help? Chat with us on Discord.

[utopian-moderator]

Thank you for your review, @portugalcoin! Keep up the good work!

Hi @duski.harahap!

Your post was upvoted by @steem-ua, new Steem dApp, using UserAuthority for algorithmic post curation!
Your post is eligible for our upvote, thanks to our collaboration with @utopian-io!
Feel free to join our @steem-ua Discord server

Hey, @duski.harahap!

Thanks for contributing on Utopian.
We’re already looking forward to your next contribution!

Get higher incentives and support Utopian.io!
Simply set @utopian.pay as a 5% (or higher) payout beneficiary on your contribution post (via SteemPlus or Steeditor).

Want to chat? Join us on Discord https://discord.gg/h52nFrV.

Vote for Utopian Witness!