Author: Janith Kasun
Translator: Frontend Xiaozhi
Source: stackabuse
There are dreams and dry goods. search 160d52a9d917e1 [Daily Move to the World] Follow the brushing wisdom who is still doing dishes in the early morning.
This article GitHub https://github.com/qq449245884/xiaozhi has been included, the first-line interview complete test site, information and my series of articles.
Introduction
In this article, we will introduce how to use Handlebars template engine Node.js
and Express
What is a template engine will be introduced, and how to use the Handlebars built service service-side rendering (SSR) Web applications.
We will also discuss how to Express.js
framework, and how to use the built-in helpers
create dynamic pages. Finally, we will learn how to develop a custom helper
when needed?.
What is a template engine
As early as the 1990s, when the Internet appeared, it was mainly used for scientific purposes, such as publishing research papers, and as a communication channel between universities and scientists. Most web pages at that time were static. The static web page is the same for every user and will not change according to every user. If you want to change any content on the page, you must do it manually.
In the modern world, things are more interactive and tailored for each user. Today, almost everyone can access the Internet. Most web applications today are dynamic. For example, on some shopping websites, different user login interfaces are displayed differently, the so-called thousands of people. For everyone, the page will follow the same template (ie continuous posting with usernames on it), but the content will be different?.
The work content of the template engine: Define the display content template, and then fill the template with the received content according to the current user and the query to the database.
We can use the template engine on the backend and the frontend. If we use a template engine to generate HTML in the backend, this method is called server-side rendering (SSR) ?.
Handlebars
Handlebars are popular in both back-end and front-end templates. For example, the popular front-end frame Ember uses Handlebars
as the template engine.
Handlebars is Mustache template language. The Mustache template language focuses on simplicity and minimal templates.
Use Handlebars in Node.js
First, create an empty folder, then open the terminal, and then run npm init -y
to create an empty Node.js project with the default configuration.
Before we start, we need to install the required Node.js libraries. express
and express-handlebars
modules by running the following commands:
npm install --save express express-handlebars
Note: use on the server side Handlebars
, you might like to use a express-handlebars
such help module that will Handlebars
integrated with web frameworks. In this article, we mainly focus on template syntax, which is why we use express-handlebars
, but if you handle template compilation and rendering yourself, you also need to see the documentation description corresponding compilation API reference
Then, recreate the default Handlebars directory structure. views
folder contains all Handlebars hand templates:
├── app.js
└── views
├── home.hbs
└── layouts
└── main.hbs
views
folder inside the layouts
folder will contain the layout or template wrapper. These layouts will contain the HTML structure, style sheets and scripts shared between the templates.
main.hbs
file is the main layout, and the home.hbs
Handlebars
template we are going to build.
In our example, we use a script to keep it simple. First, import the required libraries app.js
const express = require('express');
const exphbs = require('express-handlebars');
Then, create an Express app
const app = express();
Now, we can configure express-handlebars
as our view engine:
const express = require('express');
const exphbs = require('express-handlebars');
const app = express();
app.engine('hbs', exphbs({
defaultLayout: 'main',
extname: '.hbs'
}))
app.set('view engine', 'hbs');
By default, the extension of the Handlebars template is .handlebars
. But in the setting here, we change it to .hbs
extname
logo because it is shorter.
Next, add the Bootstrap
script and style to the main.hbs
Add the following content in home.hb
<h1>Hello World from Handlebars</h1>
Add the corresponding routing configuration in app.js
app.get('/', (req, res) => {
res.render('home');
});
Then, add the port number if it is listening:
app.listen(3000, () => {
console.log('The web server has started on port 3000');
});
So you can run node app.js
in the console to start the application.
But we can also choose to use tools such as nodemon . Using nodemon
, we don't need to restart the server every time we change the code, nodemon
will automatically refresh the server.
Disk it:
npm i -g nodemon
After installation, run:
nodemon app.js
http://localhost:3000/
in the browser:
Handlebars more features
In order to show some Handlebars
features, we will build a social media website. Here we use a simple array to simulate the database.
home.hbs
content of 060d52a9d92456 to the following:
<nav class="navbar navbar-dark bg-dark">
<a class="navbar-brand" href="#">Book Face</a>
</nav>
<div class="posts">
<div class="row justify-content-center">
<div class="col-lg-7" style="margin-top: 50px;">
<div class="card">
<img src="https://picsum.photos/500/500"
class="card-img-top" alt="...">
<div class="card-body">
<h5 class="card-title">此文章由 前端小智 发布</h5>
<ul class="list-group">
<li class="list-group-item">期待你们的留言/li>
<li class="list-group-item">期待你们的留言</li>
</ul>
</div>
</div>
</div>
</div>
</div>
Above we added a navbar
and a post display content card
, the operation effect is as follows:
Pass parameters to the template
Now, let's delete these hard-coded values from the page itself. These values are passed in by the route. Modify the following content app.js
app.get('/', function (req, res) {
res.render('home', {
post: {
author: '小智',
image: 'https://picsum.photos/500/500',
comments: []
}
});
});
The post object contains fields such as author
, image
and comments
{{post}}
in the Handlebars template to reference these values:
<nav class="navbar navbar-dark bg-dark">
<a class="navbar-brand" href="#">Book Face</a>
</nav>
<div class="posts">
<div class="row justify-content-center">
<div class="col-lg-7" style="margin-top: 50px;">
<div class="card">
<img src="https://picsum.photos/500/500"
class="card-img-top" alt="...">
<div class="card-body">
<h5 class="card-title">此文章由 {{post.author}} 发布</h5>
<ul class="list-group">
<li class="list-group-item">期待你们的留言/li>
<li class="list-group-item">期待你们的留言</li>
</ul>
</div>
</div>
</div>
</div>
</div>
The effect is as follows:
Conditions of Use
Since some logical judgment is required here, that is, comments
no data and does not display, let's see how to use conditions in the Handlebars template:
<nav class="navbar navbar-dark bg-dark">
<a class="navbar-brand" href="#">Book Face</a>
</nav>
<div class="posts">
<div class="row justify-content-center">
<div class="col-lg-7" style="margin-top: 50px;">
<div class="card">
<img src="https://picsum.photos/500/500"
class="card-img-top" alt="...">
<div class="card-body">
<h5 class="card-title">此文章由 {{post.author}} 发布</h5>
{{#if post.comments}}
<ul class="list-group">
</ul>
{{else}}
<ul class="list-group">
<li class="list-group-item">期待你们的留言</li>
</ul>
{{/if}}
</div>
</div>
</div>
</div>
</div>
Here our comments are empty, so is displayed. Looking forward to your comments.
#if
is the built-in helper of Handlebars. If the if
statement returns true
, the blocks inside the #if
block will be rendered. If it returns false
, undefined
, null
, ""
, 0
or []
, the block will not be rendered.
#if
only accepts one condition and cannot use JS comparison syntax ( ===
). If you need to use multiple conditions or other syntax, you can create a variable in the code and then pass it to the template. In addition, you can define your own helper, which we will do in the previous section.
Use loop
Since a post can contain multiple comments, we need a loop to render them. First, let's add some data:
app.get('/', function (req, res) {
res.render('home', {
post: {
author: '小智',
image: 'https://picsum.photos/500/500',
comments: [
'前端小智终身学习者',
'前端小智持续分享者',
'虽然没啥流量,但也希望你也能坚持分享下去,帮助更多的初学者 ?'
]
}
});
});
Now, in our template, use #each
loop through them:
<nav class="navbar navbar-dark bg-dark">
<a class="navbar-brand" href="#">Book Face</a>
</nav>
<div class="posts">
<div class="row justify-content-center">
<div class="col-lg-7" style="margin-top: 50px;">
<div class="card">
<img src="https://picsum.photos/500/500"
class="card-img-top" alt="...">
<div class="card-body">
<h5 class="card-title">此文章由 {{post.author}} 发布</h5>
{{#if post.comments}}
<ul class="list-group">
{{#each post.comments}}
<li class="list-group-item">{{this}}</li>
{{/each}}
</ul>
{{else}}
<ul class="list-group">
<li class="list-group-item">期待你们的留言</li>
</ul>
{{/if}}
</div>
</div>
</div>
</div>
</div>
In the #each
loop, you can use this
to refer to the elements in the current iteration. In our example, it refers to a string that is subsequently rendered
If posts
is an object array, you can also access any properties of the object. For example, if there is an array of personnel, you can simply use this.name
to access the name
field.
Now, add multiple data posts
app.get('/', function (req, res) {
res.render('home', {
posts: [
{
author: '小智',
image: 'https://picsum.photos/500/500',
comments: [
'前端小智终身学习者',
'前端小智持续分享者',
'虽然没啥流量,但也希望你也能坚持分享下去,帮助更多的初学者 ?'
]
},
{
author: '前端大智',
image: 'https://picsum.photos/500/500?2',
comments: []
}
]
});
});
Then, use #each
to traverse posts
:
<div class="posts">
<div class="row justify-content-center">
{{#each posts}}
<div class="col-lg-7" style="margin-top: 50px;">
<div class="card">
<img src="{{this.image}}" class="card-img-top" alt="...">
<div class="card-body">
<h5 class="card-title">此文章由 {{post.author}} 发布</h5>
{{#if this.comments}}
<ul class="list-group">
{{#each this.comments}}
<li class="list-group-item">{{this}}</li>
{{/each}}
</ul>
{{else}}
<ul class="list-group">
<li class="list-group-item">期待你们的留言</li>
</ul>
{{/if}}
</div>
</div>
</div>
{{/each}}
</div>
</div>
to sum up
In this article, we introduced the Handlebars
. Handlebars is a template engine for Node.js and front-end JavaScript. Using Handlebars, we can create dynamic web pages that are rendered on the server side or on the client side. Using Handlebars' condition, loop, partial and custom helper functions, our web pages will be more than just static HTML.
possible bugs after 160d52a9d92d7e code are deployed cannot be known in real time. In order to solve these bugs afterwards, a lot of time was spent on log debugging. By the way, I would like to recommend a useful BUG monitoring tool Fundebug .
Original: https://stackabuse.com/guide-to-handlebars-engine-for-node/
communicate with
The article is continuously updated every week. You can search for [Great Read it as , reply 160d52a9d92e4e [Benefit] are many front-end videos waiting for you, this article GitHub https://github.com/qq449245884/xiaozhizhizhi has been included, welcome to Star.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。