自行车车把会吧车刮坏吗
Templating engines are already a great invention — this is what I noticed again when I was working on a personal project with handlebars.js and Express recently.
模板引擎已经是一个伟大的发明-这是我最近在使用handlebars.js和Express处理个人项目时再次注意到的。
Especially large websites with dynamic features and a lot of content can be very complicated to maintain if you just start writing the HTML code in a primitive way.
如果您只是开始以原始方式编写HTML代码,则具有动态功能和大量内容的大型网站的维护可能非常复杂。
To solve this problem, you don’t have to use front-end frameworks to break everything down into reusable components.
要解决此问题,您不必使用前端框架即可将所有内容分解为可重用的组件。
Here are a few practical features of handlebars.js, which in combination with Express.js, are a lot of fun — and make developing websites a lot more comfortable.
这是handlebars.js的一些实用功能,将这些功能与Express.js结合在一起很有趣-使开发网站更加舒适。
什么是后端模板引擎? (What is a back-end templating engine?)
If you already know, of course, you can skip this intro and jump directly to our setup installation.
当然,如果您已经知道,您可以跳过此介绍,直接跳到我们的安装程序安装。
Templating engines are mainly known from the front-end. Handlebars, for example, which is often associated with Mustache.js, can also be used in the front-end. With modern back-end platforms like Express.js, you can also enter the world of Node.js.
模板引擎主要是从前端已知的。 例如,通常与Mustache.js相关联的车把也可以在前端使用。 借助Express.js之类的现代后端平台,您还可以进入Node.js的世界。
Such an engine provides a template for the server, which has to be filled with concrete data for the finished application. When the user requests the server, the server will process the template and fill it out. The user does not notice anything; he only receives the finished web page.
这种引擎为服务器提供了模板,必须为完成的应用程序填充具体数据。 当用户请求服务器时,服务器将处理模板并填写模板。 用户什么也没注意到。 他只收到完成的网页。
Templating engines are therefore ideal for creating dynamic websites that do not have to ship tons of JS code to the user, so that the front-end can be used to make API calls, for example.
因此,模板引擎非常适合创建动态网站,而这些网站不必向用户发送大量JS代码,因此,例如,前端可用于进行API调用。
The computing load is put on the server. Furthermore, templating engines make developing a web application very easy and efficient. You can break the parts down into components as if you were using a front-end framework like React or Angular.
计算负载已放在服务器上。 此外,模板引擎使开发Web应用程序变得非常容易和高效。 您可以像使用React或Angular这样的前端框架将这些部分分解为组件。
Reason enough to have a look at how we can make our life easier with handlebars.js.
有足够的理由来看看如何使用handlebars.js使我们的生活更轻松。
让我们为Express.js安装handlebars.js (Let’s install handlebars.js for Express.js)
Create a fresh directory for our project first. Then install what is needed:
首先为我们的项目创建一个新目录。 然后安装所需的内容:
npm install -y npm install express express-handlebars
Then, create a /views directory. This is the folder that express-handlebars will search for templates by default.
然后,创建一个/ views目录。 这是Express-Handlebars默认将搜索模板的文件夹。
In the views folder, we create the layout folder, which is also used by express-handlebars by default. In this folder, we create the main.handlebars — it serves as a wrapper component.
在views文件夹中,我们创建布局文件夹,默认情况下,Express-Handlebars也使用该文件夹。 在此文件夹中,我们创建main.handlebars-它充当包装器组件。
Everything we write in there will be displayed under every route of our final web app — Therefore, it is ideal for embedding SEO tags and making file imports like CSS and JS.
我们在其中编写的所有内容都将显示在最终Web应用程序的所有路径下—因此,它是嵌入SEO标签并进行文件导入(如CSS和JS)的理想选择。
Leave the main.handlebars like this: {{{body}}}
保持main.handlebars像这样: {{{body}}}
It means that we want to include here all the code that handlebars actually provides.
这意味着我们要在此处包括车把实际提供的所有代码。
The final file-structure:
最终的文件结构:
├── app.js
├── package-lock.json
└── views
├── index.handlebars
└── layouts
└── main.handlebars
app.js:
app.js:
const express = require(‘express’);const exphbs = require(‘express-handlebars’);const app = express();app.engine(‘handlebars’, exphbs());app.set(‘view engine’, ‘handlebars’);app.get(‘/’, function (req, res) {
res.render(“index”);
});app.listen(8080);
Write something into the index.handlebars, start the server, and you should see a working project.
将一些内容写入index.handlebars ,启动服务器,您将看到一个正在运行的项目。
Let’s have a look at the first cool feature for making development easier.
让我们看一下第一个很酷的功能,它使开发更容易。
传递数据并遍历数据 (Passing data and looping through it)
Giving data from Express to handlebars is really easy. The render function of express-handlebars gets an object as a second parameter, containing all data we want to provide.
将数据从Express传递到车把真的很容易。 express-handlebars的render函数将一个对象作为第二个参数,其中包含我们要提供的所有数据。
let names = ["Max", "Tom", "Anna"]app.get(‘/’, function (req, res) {
res.render(“index”, {
students: names
});
});
index.handlebars:
index.handlebars:
<h1>Students:</h1>
<ul>
{{#each students}}
<li>{{this}}</li>
{{/each}}
</ul>
Result:
结果:

Basic stuff. But what about more complex objects?
基本的东西。 但是,更复杂的对象呢?
Let’s make offer a few more details about our students:
让我们提供有关我们学生的更多详细信息:
let people = [
{name: “Max”, age: 21},
{name: “Tom”, age: 19},
{name: “Anna”, age: 25}
]
The changed index.handlebars:
更改后的index.handlebars :
<ul>
{{#each students}}
<li>{{this.name}}, {{this.age}}</li>
{{/each}}
</ul>
Result:
结果:

条件 (Conditions)
In my current just-for-fun side project, I had the problem that I did not only want to display something under a true condition — also, if this condition is false, something else must be displayed at another place.
在我当前的有趣游戏项目中,我遇到的问题是,我不仅要显示真实条件下的内容,而且,如果此条件为假,则还必须在其他位置显示其他内容。
Yes, it sounds complicated, but actually it is not — here the real example:
是的,这听起来很复杂,但实际上并非如此,在这里是真实的示例:

On the left and also on the right, under the JavaScript code, you see the same info-box — both boxes have the same CSS-styles, of course.
在JavaScript代码的左侧和右侧,您将看到相同的信息框-当然,两个框都具有相同CSS样式。
But on the left side, the box is still rounded at the top corners. Thanks to the conditionals in handlebars, I don’t need to create a single component for both, but can solve it in the following way:
但是在左侧,该框仍在顶部角落处是圆形的。 由于车把中的条件,我不需要为两个都创建一个组件,而是可以通过以下方式解决它:
- If some source code is passed for display, it is automatically displayed above the infobox. 如果传递了一些源代码进行显示,它将自动显示在信息框上方。
- If no source code is passed, then the infobox is displayed alone. 如果没有传递源代码,则仅显示信息框。
- How to solve the problem with rounded corners? Also, in the infobox component itself, it is checked if source code for displaying is provided. 如何解决圆角问题? 另外,在信息框组件本身中,检查是否提供了用于显示的源代码。
- In case no source code is passed, another CSS class is given to the infobox, which rounds the upper corners. 如果未传递源代码,则将另一个CSS类提供给信息框,该框将使圆角变圆。
So I can use the same infobox component everywhere and, in special cases, handlebars automatically, with a check. Of course, you need the use of conditionals; here is how to do this with handlebars:
因此,我可以在各处使用相同的信息框组件,在特殊情况下,请选中并自动使用车把。 当然,您需要使用条件句; 这是使用把手的方法:
检查条件是否正确-如果 (Check condition for truth — if)
Therefore we change the app.js a little bit:
因此,我们对app.js进行了一些更改:
let person = {
name: “Max”,
adult: false
}app.get(‘/’, function (req, res) {
res.render(“index”, {
person: person
});
});
index.handlebars:
index.handlebars:
{{#if person.adult}}
<p>person is an adult</p>
{{/if}}
And now, you should see nothing, since an adult is false. The problem is that in handlebars, there is no real else. What we need to use instead is unless, which is the inverse of if in this templating language:
而现在,您将一无所获,因为一个成年人是假的。 问题是在车把上没有别的东西。 相反,我们需要使用的是,除非,这与模板语言中if的相反:
{{#unless person.adult}}
<p>not an adult.</p>
{{/unless}}
Now you should see “not an adult.” on the website.
现在您应该看到“不是成年人”。 在网站上。
“ {{}}”和“ {{{}}}”之间的区别 (The difference between ‘{{ }}’ and ‘{{{ }}}’)
This is a common mistake that many beginners of handlebars make. If we want to pass something with handlebars into our template, we can do this in two ways:
这是许多把手初学者常犯的错误。 如果要将带把手的东西传递到模板中,可以采用两种方法:
- Providing content, which is then displayed between our HTML tags. 提供内容,然后显示在我们HTML标签之间。
- HTML structures, which are also rendered correctly. HTML结构,也可以正确呈现。
Here is an example to show this:
这是显示此的示例:
let content = “<b>I am bold text</b>”app.get(‘/’, function (req, res) {
res.render(“index”, {
content: content
});
});
index.handlebars: {{content}}
index.handlebars : {{content}}
This will lead to displaying as text:
这将导致显示为文本:

3 curly brackets instead of just 2 will force handlebars to consider the content as valid HTML code:
3个大括号(而不是2个)将迫使车把将内容视为有效HTML代码:
{{{content}}}
:
{{{content}}}
:

In my side project, I used this when I wanted to display italic or bold words for the code cheatsheets' headlines.
在我的辅助项目中,当我要在代码备忘单标题上显示斜体或粗体字时,使用了此选项。
感谢您的阅读! (Thank you for reading!)
普通英语JavaScript(JavaScript In Plain English)
Enjoyed this article? If so, get more similar content by subscribing to Decoded, our YouTube channel!
喜欢这篇文章吗? 如果是这样,请订阅我们的YouTube频道解码,以获得更多类似的内容!
翻译自: https://medium.com/javascript-in-plain-english/express-handlebars-dd2fb85e265d
自行车车把会吧车刮坏吗