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.
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.
Server Side Rendering (SSR).
Handlebars are popular in both backend and frontend templates. For example, the popular front-end framework Ember uses Handlebars as its template engine.
npm init -yCreate an empty folder with the default configuration Node.js project.
express and
express-handlebars modules by running the following command:
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.
views folder contains all Handlebars hand templates: The
layouts
├── app.js └── views ├── home.hbs └── layouts └── main.hbs
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.
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- 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');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.
Bootstrap script and style to the
main.hbs layout:
home.hb :
<h1 id="Hello-World-from-Handlebars">Hello World from Handlebars</h1>Add the corresponding routing configuration in
app.js:
app.get('/', (req, res) => { res.render('home'); });Then, add the listening port number:
app.listen(3000, () => { console.log('The web server has started on port 3000'); });This way The application can be started by running
node app.js in the console.
nodemon, we don’t need to restart the server every time when changing the code,
nodemon will automatically refresh the server.
npm i -g nodemonAfter installation, run:
nodemon app.jsOpen in browser
http://localhost:3000/:
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/imghwm/default1.png" data-src="https://picsum.photos/500/500" alt="Understanding the Template Engine in Node (Getting Started)" > </p><p> </p><h5 id="此文章由-前端小智-发布">此文章由 前端小智 发布</h5>
- 期待你们的留言/li>
- 期待你们的留言
上面我们添加了一个 navbar
和一个帖子的展示内容 card
,运行效果如下:
向模板传递参数
现在,让我们从页面本身中删除这些硬编码的值,这些值由路由传递进来, 在 app.js
中修改如下内容 :
app.get('/', function (req, res) { res.render('home', { post: { author: '小智', image: 'https://picsum.photos/500/500', comments: [] } }); });
post 对象包含author
,image
和comments
等字段。 我们可以在 Handlebars模板使用{{post}}
来引用这些值:
<nav> <a>Book Face</a> </nav> <p> </p><p> </p><p> </p><p> <img class="card-img-top lazy" src="/static/imghwm/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>
- 期待你们的留言/li>
- 期待你们的留言
效果如下:
使用条件
由于这里需要一些逻辑判断,即 comments
没数据不显示,我们看看如何在Handlebars 模板中使用条件:
<nav> <a>Book Face</a> </nav> <p> </p><p> </p><p> </p><p> <img class="card-img-top lazy" src="/static/imghwm/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}}
- 期待你们的留言
这里我们的 comments 为空,所以显示了 期待你们的留言
。
#if
是把 Handlebars 的内置帮助器。 如果if
语句返回true
,则将渲染#if
块内部的块。 如果返回false
,undefined
,null
,""
,0
或[]
,则不会渲染该块。
#if
仅接受一个条件,并且不能使用 JS 比较语法(===
)。 如果需要使用多个条件或其他语法,则可以在代码中创建一个变量,然后将其传递给模板。 另外,你可以定义自己的 helper ,我们将在上一节中进行操作。
使用循环
由于帖子可以包含多个评论,因此我们需要一个循环渲染它们。 首先,我们先添加一些数据:
app.get('/', function (req, res) { res.render('home', { post: { author: '小智', image: 'https://picsum.photos/500/500', comments: [ '前端小智终身学习者', '前端小智持续分享者', '虽然没啥流量,但也希望你也能坚持分享下去,帮助更多的初学者' ] } }); });
现在,在我们的模板中,使用#each
循环遍历它们:
<nav> <a>Book Face</a> </nav> <p> </p><p> </p><p> </p><p> <img class="card-img-top lazy" src="/static/imghwm/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}}
-
{{#each post.comments}}
- {{this}} {{/each}}
- 期待你们的留言
在#each
循环中,可以使用this
来引用当前迭代中的元素。在我们的示例中,它引用了一个随后被渲染的字符串
如果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: [] } ] }); });
然后,使用#each
来遍历 posts
:
<p> </p><p> {{#each posts}} </p><p> </p><p> <img class="card-img-top lazy" src="/static/imghwm/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}}
-
{{#each this.comments}}
- {{this}} {{/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!

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Atom editor mac version download
The most popular open source editor

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SublimeText3 Mac version
God-level code editing software (SublimeText3)

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment
