一、准备工作
-
安装 Node.js。
-
创建一个新的 Node.js 项目,使用 npm 初始化一个 package.json 文件,并安装 express 和 jade 依赖:
$ npm init -y
$ npm install express jade --save
二、创建一个使用 jade 模板引擎的简单应用
- 创建 index.js 文件,输入以下代码:
// index.js
const express = require('express');
const app = express();
// set the view engine to jade
app.set('view engine', 'jade');
// render index.jade on the homepage
app.get('/', function(req, res) {
res.render('index', { title: 'Welcome' });
});
// start the server
app.listen(3000, function() {
console.log('Server started on port 3000');
});
- 创建 index.jade 文件,输入以下代码:
// index.jade
html
head
title= title
body
h1 Welcome to my website!
- 运行应用:
$ node index.js
- 打开浏览器并访问 http://localhost:3000/ ,即可看到页面上输出 “Welcome to my website!”。
三、jade 模板引擎的基础语法
- 输出变量值:
p= someVariable
- 使用 if-else 语句:
- if(someCondition) {
p This will show up if `someCondition` is true.
- } else {
p This will show up if `someCondition` is false.
- }
四、使用 jade 模板引擎的进阶示例
- 创建一个包含 if-else 语句的页面:
// login.jade
html
head
title Log In
body
h1 Log In to My Website
- if(error) {
p(style='color: red;') Incorrect username or password.
- }
form(action='/login', method='POST')
label(for='username') Username:
input(type='text', name='username')
label(for='password') Password:
input(type='password', name='password')
button(type='submit') Log In
- 在服务器端判断用户名和密码是否正确,如果不正确则把 error 设为 true,并渲染登录页面;如果正确则渲染成功页面:
// index.js
// ...
app.get('/login', function(req, res) {
res.render('login');
});
app.post('/login', function(req, res) {
var username = req.body.username;
var password = req.body.password;
if(username === 'admin' && password === '123456') {
res.render('success');
} else {
res.render('login', { error: true });
}
});
// ...
- 创建成功页面:
// success.jade
html
head
title Success
body
h1 Congratulations!
p You have successfully logged in to my website.
- 运行应用并访问 http://localhost:3000/login ,即可看到登录页面。如果输入正确的用户名和密码,将跳转到成功页面;如果输入错误的用户名或密码,则提示错误信息并返回登录页面。
以上是使用 Node.js 和 jade 模板引擎的示例攻略。通过学习这些示例,您可以了解如何使用 jade 模板引擎渲染动态网页,以及如何使用基本语法和条件语句使用 jade 模板引擎。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Node.js 使用jade模板引擎的示例 - Python技术站