Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the template engines in Node and JavaScript

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article is to share with you about the template engine in Node/JavaScript, the editor thinks it is very practical, so I share it with you to learn. I hope you can get something after reading this article.

Brief introduction

We will show you how to use the Handlebars template engine with Node.js and Express. It also describes what a template engine is and how to use Handlebars to build a server-side rendering (SSR) web application.

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 will learn how to develop a custom helper when needed.

What is a template engine?

As early as the 1990s, when the Internet emerged, it was mainly used for scientific purposes, such as publishing research papers and as a channel of communication between universities and scientists. At that time, most web pages were static. Static web pages are the same for each user and do not change on a per-user basis, and must be done manually if you want to change anything on the page.

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, in some shopping sites, different users login interface, the display is not the same, the so-called thousand people thousand faces. For everyone, the page will follow the same template (that is, successive posts with a user name on it), but the content will be different.

The work of the template engine: define the presentation content template, and then populate the template with the received content according to the current user and the query to the database.

We can use template engines on both the back end and the front end. If we use a template engine to generate HTML on the back end, this approach is called server-side rendering (SSR).

Handlebars

Handlebars is popular in both back-end and front-end templates. For example, the popular front-end framework Ember uses Handlebars as the 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-y to create an empty Node.js project with the default configuration.

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. In this article, we 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 for compilation API reference.

Then, recreate the default Handlebars directory structure. The views folder contains all Handlebars hand templates:

├── app.js └── views ├── home.hbs └── layouts └── main.hbs

The layouts folder within the 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')

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 setup here, we change it to .hbs with the extname flag, because it's shorter.

Next, add Bootstrap scripts and styles to the main.hbs layout:

Add the following to home.hb:

Hello World from Handlebars

Add the corresponding routing configuration to app.js:

App.get ('/', (req, res) = > {res.render ('home');})

Then, add the port number if you are listening:

App.listen (3000, () = > {console.log ('The web server has started on port 3000');})

This allows you to run node app.js in the console to launch the application.

But we can also choose to use tools such as nodemon. With nodemon, we don't have to restart the server every time we change the code. Nodemon will refresh the server automatically.

Disk it:

Npm I-g nodemon

After installation, run:

Nodemon app.js

Open http://localhost:3000/ in the browser:

Handlebars more Featur

To demonstrate some Handlebars features, we will build a social media-like website. Here we use a simple array to simulate the database.

Update the home.hbs content as follows:

Book Face

...

This article is posted by front-end Xiaozhi looking forward to your message / li > looking forward to your message.

Above, we added a navbar and a card of the display content of a post. The results are as follows:

Pass parameters to the template

Now, let's remove these hard-coded values from the page itself, which are passed in by route, and modify the following in app.js:

App.get ('/', function (req, res) {res.render ('home', {post: {author:' small Intelligence', image: 'https://picsum.photos/500/500', comments: []}})

The post object contains fields such as author,image and comments. We can use {{post}} in the Handlebars template to reference these values:

Book Face

...

This article is posted by {{post.author}} looking forward to your comments / li > looking forward to your comments.

The effect is as follows:

Conditions of use

Since some logical judgments are needed here, that is, comments cannot be displayed without data, let's take a look at how to use conditions in the Handlebars template:

Book Face

...

This article is posted by {{post.author}} {{# if post.comments}} {{else}} looking forward to your message {{/ if}}

Our comments is empty here, so we are looking forward to your message.

# if is a built-in helper for Handlebars. If the if statement returns true, the block inside the # if block is rendered. If false,undefined,null, "", 0, or [] is returned, the block will not be rendered.

# if accepts only one condition and cannot use the JS comparison syntax (=). If you need to use multiple conditions or other syntax, you can create a variable in your code and pass it to the template. In addition, you can define your own helper, which we will do in the previous section.

Use cycle

Since posts 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:' small Intelligence', image: 'https://picsum.photos/500/500', comments: [' lifelong Learner of Front-end Intelligence', 'continuous sharing of Front-end Intelligence', 'although there is no traffic But I also hope you can keep sharing and help more beginners']}) })

Now, in our template, use the # each loop to iterate through them:

Book Face

...

This article was published by {{post.author}} {{# if post.comments}} {{# each post.comments}} {{this}} {{/ each}} {{else}} look forward to your message {{/ if}}

In the # each loop, you can use this to refer to elements in the current iteration. In our example, it refers to a string that is then rendered.

If posts is an array of objects, you can also access any of the properties of that object. For example, if you have an array of people, you can simply use this.name to access the name field.

Now, add multiple pieces of data to our posts:

App.get ('/', function (req, res) {res.render ('home', {posts: [{author:' image', 'https://picsum.photos/500/500', comments:' front-end intelligence lifelong learner', 'front-end intelligence continuous distributor' Although there is not much traffic But I also hope you can keep sharing and help more beginners']}, {author: 'front-end wisdom', image: 'https://picsum.photos/500/500?2', comments: []}) })

Then, use # each to traverse the posts:

{{# each posts}}

...

This article was published by {{post.author}} {{# if this.comments}} {{# each this.comments}} {{this}} {{/ each}} {{else}} look forward to your message {{/ if}} {{/ each}}

Handlebars is the template engine for Node.js and front-end JavaScript. With Handlebars, we can create dynamic web pages rendered on the server side or on the client side. Using Handlebars's conditional, loop, local and custom helper features, our web page will be more than just static HTML.

This is what the template engine in Node/JavaScript looks like, and the editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report