Expressjs教程

Express.js 模板引擎

什么是模板引擎

模板引擎可帮助您在应用程序中使用静态模板文件。在运行时,它将用实际值替换模板文件中的变量,并将模板转换为发送给客户端的HTML文件。因此,首选这种方法来轻松设计HTML页面。
以下是可与Express.js一起使用的一些流行模板引擎的列表:
Pug (formerly known as jade) mustache dust atpl eco ect ejs haml haml-coffee handlebars hogan jazz jqtpl JUST liquor QEJS swig templayed toffee underscore walrus whiskers
在上述模板引擎中,pug(以前称为玉)和胡须似乎是最受欢迎的选择。 Pug与使用空白的Haml相似。根据模板基准,pug比Handlebars,EJS和Underscore慢2倍。 ECT似乎是最快的。许多程序员喜欢mustache模板引擎,主要是因为它是最简单和通用的模板引擎之一。

将模板引擎与Express配合使用

模板引擎使您能够在应用程序中使用静态模板文件。要渲染模板文件,您必须设置以下应用程序设置属性:
视图:它指定模板文件所在的目录。
例如: app.set('views','./views')。
视图引擎: : 它指定您使用的模板引擎。例如,要使用Pug模板引擎: app.set('view engine','pug')。
我们来看看模板引擎哈巴狗(以前称为玉)。

Pug模板引擎

让我们学习如何使用Express.js在Node.js应用程序中使用Pug模板引擎。 Pug是Node.js的模板引擎。 Pug使用空格和缩进作为语法的一部分。

安装pug

执行以下命令以安装pug模板引擎:
npm install pug--save
Express.js模板引擎
Pug模板必须写在.pug文件中,所有.pug文件都必须放在views文件夹中
注意: 默认情况下,Express.js在根文件夹下的views文件夹中搜索所有视图。您还可以使用express中的views属性将其设置为另一个文件夹。例如: app.set('views','MyViews')。
pug模板引擎以简单的方式获取输入并以HTML生成输出。查看它如何呈现HTML:
简单输入:
doctype html
html
    head
        title A simple pug example
    body
        h1 this page is produced by pug template engine
        p some paragraph here.. 
帕格模板产生的输出:
<!DOCTYPE html>
<html>
  <head>
    <title>A simple pug example</title>
  </head>
  <body>
    <h1>this page is produced by pug template engine</h1>
    <p>some paragraph here..</p>
  </body>
</html>
Express.js可与任何模板引擎一起使用。让我们以一个示例来部署pug模板如何动态创建HTML页面。
请参见以下示例:
创建一个名为 index.pug <的文件 strong> 文件放入views文件夹中,并在其中写入以下pug模板:
doctype html
html
    head
        title A simple pug example
    body
        h1 this page is produced by pug template engine
        p some paragraph here.. 
文件: server.js
var express = require('express');
var app = express();
//set view engine
app.set("view engine","pug")
app.get('/', function (req, res) {
res.render('view.pug', index);
 res.render('index');
});
var server = app.listen(5000, function () {
    console.log('Node server is running..');
});
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4