Table of Contents
Hello World from Handlebars
Handlebars 更多功能
此文章由 前端小智 发布
向模板传递参数
此文章由 {{post.author}} 发布
使用条件
使用循环
总结
Home Web Front-end JS Tutorial Understanding the Template Engine in Node (Getting Started)

Understanding the Template Engine in Node (Getting Started)

Oct 30, 2020 pm 05:38 PM
javascript node front end template engine

Understanding the Template Engine in Node (Getting Started)

Recommended tutorial: node js tutorial

In this article, we will introduce how to use Node. js and Express to use the Handlebars template engine. We will also introduce what a template engine is and how to use Handlebars to build server-side rendering (SSR) web applications.

We will also discuss how to configure Handlebars using the

Express.js framework, and how to create dynamic pages using the built-in helpers. Finally, we'll see how to develop a custom helper if needed.

What is a template engine

Back in the 1990s, when the Internet emerged, 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. Static web pages are the same for every user and do not change for every user. If you want to change anything on the page, you must do it manually.

In the modern world, things are more interactive and customized for each user. Today, almost everyone has access to the Internet. Most web applications today are dynamic. For example, on some shopping websites, the interfaces for different users to log in are displayed differently, so-called thousands of people have different views. The page will follow the same template for everyone (i.e. consecutive posts with the username 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 based on the current user and the query to the database.

We can use template engines in both backend and frontend. If we use a template engine on the backend to generate HTML, this method is called

Server Side Rendering (SSR).

Handlebars

Handlebars are popular in both backend and frontend templates. For example, the popular front-end framework Ember uses Handlebars as its template engine.

Handlebars is an extension of the Mustache template language, which focuses on simplicity and minimal templates.

Using Handlebars in Node.js

First, create an empty folder, then open the terminal, and then run

npm init -yCreate an empty folder with the default configuration Node.js project.

Before we begin, we need to install the required Node.js libraries. Install the

express and express-handlebars modules by running the following command:

npm install --save express express-handlebars

NOTE :When using Handlebars on the server side, you may use a helper module like express-handlebars which integrates Handlebars with the web framework together. 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 read the documentation corresponding to the compilation API reference.

Then, re-create the default Handlebars directory structure. The

views folder contains all Handlebars hand templates: The layouts

folder inside the

├── app.js
└── views
    ├── home.hbs
    └── layouts
        └── main.hbs
Copy after login
views folder will contain the layout or template wrapper. These layouts will contain HTML structures, stylesheets and scripts shared between templates. The

main.hbs file is the main layout and the home.hbs file is the sample Handlebars template we want to build.

In our example, we use a script to keep it simple. First, import the required libraries in the

app.js file:

const express = require('express');
const exphbs = require('express-handlebars');
Copy after login
Then, create an Express app

const app = express();
Copy after login
Now, we can configure

express- handlebarsAs 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');
Copy after login
By default, the extension of the Handlebars template is

.handlebars. But in the settings here, we change it to .hbs via the extname flag because it is shorter.

Next, add the

Bootstrap script and style to the main.hbs layout:

Add the following content to

home.hb :

<h1 id="Hello-World-from-Handlebars">Hello World from Handlebars</h1>
Copy after login
Add the corresponding routing configuration in

app.js:

app.get('/', (req, res) => {
    res.render('home');
});
Copy after login
Then, add the listening port number:

app.listen(3000, () => {
    console.log('The web server has started on port 3000');
});
Copy after login
This way The application can be started by running

node app.js in the console.

But we can also choose to use tools such as nodemon. Using

nodemon, we don’t need to restart the server every time when changing the code, nodemon will automatically refresh the server.

Disk it:

 npm i -g nodemon
Copy after login
After installation, run:

 nodemon app.js
Copy after login
Open in browser

http://localhost:3000/:

Understanding the Template Engine in Node (Getting Started)

Handlebars 更多功能

为了展示一些Handlebars功能,我们将构建一个社交媒体类的网站。 这里我们用一个简单的数组来模拟数据库。

home.hbs内容更新成如下:

<nav>
    <a>Book Face</a>
</nav>

<p>
    </p><p>
        </p><p>
            </p><p>

                <img  class="card-img-top lazy" src="/static/imghw/default1.png" data-src="https://picsum.photos/500/500" alt="Understanding the Template Engine in Node (Getting Started)" >
                </p><p>
                    </p><h5 id="此文章由-前端小智-发布">此文章由 前端小智 发布</h5>

                    
Copy after login
                            
  • 期待你们的留言/li>                         
  • 期待你们的留言
  •                     
                                           

上面我们添加了一个 navbar 和一个帖子的展示内容 card,运行效果如下:

Understanding the Template Engine in Node (Getting Started)

向模板传递参数

现在,让我们从页面本身中删除这些硬编码的值,这些值由路由传递进来, 在 app.js 中修改如下内容 :

app.get('/', function (req, res) {
    res.render('home', {
        post: {
            author: '小智',
            image: 'https://picsum.photos/500/500',
            comments: []
        }
    });
});
Copy after login

post 对象包含author,imagecomments等字段。 我们可以在 Handlebars模板使用{{post}}来引用这些值:

<nav>
    <a>Book Face</a>
</nav>

<p>
    </p><p>
        </p><p>
            </p><p>

                <img  class="card-img-top lazy" src="/static/imghw/default1.png" data-src="https://picsum.photos/500/500" alt="Understanding the Template Engine in Node (Getting Started)" >
                </p><p>
                    </p><h5 id="此文章由-post-author-发布">此文章由 {{post.author}} 发布</h5>

                    
Copy after login
                            
  • 期待你们的留言/li>                         
  • 期待你们的留言
  •                     
                                           

效果如下:

Understanding the Template Engine in Node (Getting Started)

使用条件

由于这里需要一些逻辑判断,即 comments 没数据不显示,我们看看如何在Handlebars 模板中使用条件:

<nav>
    <a>Book Face</a>
</nav>

<p>
    </p><p>
        </p><p>
            </p><p>

                <img  class="card-img-top lazy" src="/static/imghw/default1.png" data-src="https://picsum.photos/500/500" alt="Understanding the Template Engine in Node (Getting Started)" >
                </p><p>
                    </p><h5 id="此文章由-post-author-发布">此文章由 {{post.author}} 发布</h5>
                    {{#if post.comments}}
                    
Copy after login
Copy after login
                        
                    {{else}}                     
                            
  • 期待你们的留言
  •                     
                    {{/if}}                                            

这里我们的 comments 为空,所以显示了 期待你们的留言

Understanding the Template Engine in Node (Getting Started)

#if是把 Handlebars 的内置帮助器。 如果if语句返回true,则将渲染#if块内部的块。 如果返回falseundefinednull""0[],则不会渲染该块。

#if仅接受一个条件,并且不能使用 JS 比较语法(===)。 如果需要使用多个条件或其他语法,则可以在代码中创建一个变量,然后将其传递给模板。 另外,你可以定义自己的 helper ,我们将在上一节中进行操作。

使用循环

由于帖子可以包含多个评论,因此我们需要一个循环渲染它们。 首先,我们先添加一些数据:

app.get('/', function (req, res) {
  res.render('home', {
      post: {
          author: '小智',
          image: 'https://picsum.photos/500/500',
          comments: [
            '前端小智终身学习者',
            '前端小智持续分享者',
            '虽然没啥流量,但也希望你也能坚持分享下去,帮助更多的初学者'
          ]
      }
  });
});
Copy after login

现在,在我们的模板中,使用#each循环遍历它们:

<nav>
    <a>Book Face</a>
</nav>

<p>
    </p><p>
        </p><p>
            </p><p>

                <img  class="card-img-top lazy" src="/static/imghw/default1.png" data-src="https://picsum.photos/500/500" alt="Understanding the Template Engine in Node (Getting Started)" >
                </p><p>
                    </p><h5 id="此文章由-post-author-发布">此文章由 {{post.author}} 发布</h5>
                    {{#if post.comments}}
                    
Copy after login
Copy after login
                          {{#each post.comments}}                       
  • {{this}}
  •                       {{/each}}                     
                    {{else}}                     
                            
  • 期待你们的留言
  •                     
                    {{/if}}                                            

#each循环中,可以使用this来引用当前迭代中的元素。在我们的示例中,它引用了一个随后被渲染的字符串

Understanding the Template Engine in Node (Getting Started)

如果posts是一个对象数组,你也可以访问该对象的任何属性。例如,如果有一个人员数组,你可以简单地使用this.name来访问name字段。

现在,为我们的 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: []
        }
      ]
  });
});
Copy after login

然后,使用#each来遍历 posts

<p>
    </p><p>
      {{#each posts}}
        </p><p>
            </p><p>
                <img  class="card-img-top lazy" src="/static/imghw/default1.png" data-src="{{this.image}}" alt="Understanding the Template Engine in Node (Getting Started)" >
                </p><p>
                    </p><h5 id="此文章由-post-author-发布">此文章由 {{post.author}} 发布</h5>
                    {{#if this.comments}}
                    
Copy after login
                          {{#each this.comments}}                       
  • {{this}}
  •                       {{/each}}                     
                    {{else}}                     
                            
  • 期待你们的留言
  •                     
                    {{/if}}                                              {{/each}}     

总结

在本文中,我们介绍了Handlebars的基础知识,Handlebars 是Node.js 和前端JavaScript 的模板引擎。 使用 Handlebars,我们可以创建在服务器端或客户端渲染的动态网页。 使用 Handlebars 的条件,循环,局部和自定义帮助器功能,我们的网页将不仅仅是静态HTML。

原文地址:https://stackabuse.com/guide-to-handlebars-engine-for-node/

作者:Janith Kasun

译者:前端小智

更多编程相关知识,请访问:编程入门!!

The above is the detailed content of Understanding the Template Engine in Node (Getting Started). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1269
29
C# Tutorial
1248
24
Pi Node Teaching: What is a Pi Node? How to install and set up Pi Node? Pi Node Teaching: What is a Pi Node? How to install and set up Pi Node? Mar 05, 2025 pm 05:57 PM

Detailed explanation and installation guide for PiNetwork nodes This article will introduce the PiNetwork ecosystem in detail - Pi nodes, a key role in the PiNetwork ecosystem, and provide complete steps for installation and configuration. After the launch of the PiNetwork blockchain test network, Pi nodes have become an important part of many pioneers actively participating in the testing, preparing for the upcoming main network release. If you don’t know PiNetwork yet, please refer to what is Picoin? What is the price for listing? Pi usage, mining and security analysis. What is PiNetwork? The PiNetwork project started in 2019 and owns its exclusive cryptocurrency Pi Coin. The project aims to create a one that everyone can participate

PHP and Vue: a perfect pairing of front-end development tools PHP and Vue: a perfect pairing of front-end development tools Mar 16, 2024 pm 12:09 PM

PHP and Vue: a perfect pairing of front-end development tools. In today's era of rapid development of the Internet, front-end development has become increasingly important. As users have higher and higher requirements for the experience of websites and applications, front-end developers need to use more efficient and flexible tools to create responsive and interactive interfaces. As two important technologies in the field of front-end development, PHP and Vue.js can be regarded as perfect tools when paired together. This article will explore the combination of PHP and Vue, as well as detailed code examples to help readers better understand and apply these two

Is Django front-end or back-end? check it out! Is Django front-end or back-end? check it out! Jan 19, 2024 am 08:37 AM

Django is a web application framework written in Python that emphasizes rapid development and clean methods. Although Django is a web framework, to answer the question whether Django is a front-end or a back-end, you need to have a deep understanding of the concepts of front-end and back-end. The front end refers to the interface that users directly interact with, and the back end refers to server-side programs. They interact with data through the HTTP protocol. When the front-end and back-end are separated, the front-end and back-end programs can be developed independently to implement business logic and interactive effects respectively, and data exchange.

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Exploring Go language front-end technology: a new vision for front-end development Exploring Go language front-end technology: a new vision for front-end development Mar 28, 2024 pm 01:06 PM

As a fast and efficient programming language, Go language is widely popular in the field of back-end development. However, few people associate Go language with front-end development. In fact, using Go language for front-end development can not only improve efficiency, but also bring new horizons to developers. This article will explore the possibility of using the Go language for front-end development and provide specific code examples to help readers better understand this area. In traditional front-end development, JavaScript, HTML, and CSS are often used to build user interfaces

Django: A magical framework that can handle both front-end and back-end development! Django: A magical framework that can handle both front-end and back-end development! Jan 19, 2024 am 08:52 AM

Django: A magical framework that can handle both front-end and back-end development! Django is an efficient and scalable web application framework. It is able to support multiple web development models, including MVC and MTV, and can easily develop high-quality web applications. Django not only supports back-end development, but can also quickly build front-end interfaces and achieve flexible view display through template language. Django combines front-end development and back-end development into a seamless integration, so developers don’t have to specialize in learning

Questions frequently asked by front-end interviewers Questions frequently asked by front-end interviewers Mar 19, 2024 pm 02:24 PM

In front-end development interviews, common questions cover a wide range of topics, including HTML/CSS basics, JavaScript basics, frameworks and libraries, project experience, algorithms and data structures, performance optimization, cross-domain requests, front-end engineering, design patterns, and new technologies and trends. . Interviewer questions are designed to assess the candidate's technical skills, project experience, and understanding of industry trends. Therefore, candidates should be fully prepared in these areas to demonstrate their abilities and expertise.

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

See all articles