当前位置:网站首页>小试牛刀之NunJucks模板引擎
小试牛刀之NunJucks模板引擎
2022-07-07 17:25:00 【抗争的小青年】
NunJucks模板引擎
模板引擎有很多,我之前就曾用过ejs,都是对页面进行渲染.接下来带大家简单体验一下Nunjucks。真别说,插值语法有点vue的那股味道了。
初试NunJucks模板引擎
- 先创建项目文件夹
nunjucksExprice - 初始化项目文件
npm init -y
- 引入NumJucks
提示
终端输入
npm install nunjucks
等待安装完成后,我们在安装express.js,来搭建一个服务器。
- 引入express.js
npm install express
- 创建视图文件夹
view - 在视图文件夹中创建
index.html文件 - 创建项目入口文件
index.js - 使用express创建服务器
const express = require("express")
const app = express()
app.listen('80', () => {
console.log('express is running at http://127.0.0.1/');
})
一个简单的服务器就创建好了。
- 在入口文件中引入
nunjucks,并使用node.js自带的path模块设置模板路径。
const express = require("express")
const nunjucks = require("nunjucks")
const path = require("path")
const app = express()
//设置模板存储位置
app.set("view", path.join(__dirname, "view"))
//设置模板引擎
nunjucks.configure("view", {
autoescape: true, //是否自动匹配
express: app
})
//设置视图引擎
app.set("view engine", "html")
//设置路由,进行页面渲染
app.get("/", (req, res) => {
res.render("index")
})
app.listen('80', () => {
console.log('express is running at http://127.0.0.1/');
})
上面的代码也可以这样写,这两种写法是等价的,唯一不同的区别在于一个设置了视图引擎,所以在渲染页面的时候
不用加.html后缀,一个没有设置,就需要加上.html后缀,否则模板引擎找不到页面。const express = require("express") const nunjucks = require("nunjucks") const path = require("path") const app = express() //设置模板存储位置 app.set("view", path.join(__dirname, "view")) //设置模板引擎 nunjucks.configure("view", { autoescape: true, //是否自动匹配 express: app }) app.get("/", (req, res) => { res.render("index.html") }) app.listen('80', () => { console.log('express is running at http://127.0.0.1/'); })
功能小试
接下来和我一起了解一下NumJucks的使用方法吧。
和ejs一样,NumJucks在渲染页面的时候也可以传值(key:value)的形式。
传递变量
我们创建一个变量str
str = 'Word'
app.get("/", (req, res) => {
res.render("index.html",{
str})
})
str:ES6语法,键值一样写一个就行。
在页面中这样使用
{
{
str}}
循环遍历
我们创建一个数组
let list = ['橘子', '桃子', '西瓜']
app.get("/", (req, res) => {
res.render("index.html",{
list})
})
在页面中这样使用
<ul>
{% for item in list%}
<li>{
{item}}</li>
{% endfor %}
</ul>
可以看到它的使用方式不再和
ejs一样,ejs的模板语法为<%%>,这里要稍加区分。同时在循环结尾处,必须要有 {% endfor %}
我们创建一个对象数组
var items = [{
name: '张三', age: 20 }, {
name: '王五', age: 19 }]
在页面中这样使用
<ul>
{
% for item in items%}
<ol>{
{
item.name}} - {
{
item['age']}}</ol>
{
% endfor%}
</ul>
判断
我们创建一个布尔类型变量
var isDelete = true
app.get("/", (req, res) => {
res.render("index.html",{
isDelete})
})
在页面中这样使用
{% if isDelete %}
<h3>欢迎登陆</h3>
{% else %}
<h3>请登陆</h3>
{% endif %}
同样,{%endif%} 也是不可缺少的。
因为isDelete的值是true,那么页面会显示"欢迎登陆"
输出效果

项目目录

这里就带大家体验了平时开发中比较常用的功能了,更多用法请到官方文档查阅。我已经放到本文首了,方便大家查阅。
边栏推荐
- Flipping game (enumeration)
- Scientists have observed for the first time that the "electron vortex" helps to design more efficient electronic products
- 2022.07.02
- how to prove compiler‘s correctness
- L1-023 output gplt (Lua)
- “本真”是什么意思
- Golang client server login
- PV静态创建和动态创建
- For friends who are not fat at all, nature tells you the reason: it is a genetic mutation
- 虚拟数字人里的生意经
猜你喜欢

The strength index of specialized and new software development enterprises was released, and Kirin Xin'an was honored on the list
![[tpm2.0 principle and Application guide] Chapter 9, 10 and 11](/img/7f/0d4d91142bc3d79ea445a8f64afba7.png)
[tpm2.0 principle and Application guide] Chapter 9, 10 and 11

Numpy——axis

杰理之发起对耳配对、回连、开启可发现、可连接的轮循函数【篇】
![[Blue Bridge Cup training 100 questions] sort scratch from small to large. Blue Bridge Cup scratch competition special prediction programming question centralized training simulation exercise question](/img/08/5f4b4e2700606554516807c01454fd.png)
[Blue Bridge Cup training 100 questions] sort scratch from small to large. Blue Bridge Cup scratch competition special prediction programming question centralized training simulation exercise question

Responsibility chain model - unity

Do you know all four common cache modes?

Kunpeng developer summit 2022 | Kirin Xin'an and Kunpeng jointly build a new ecosystem of computing industry

Netease Yunxin participated in the preparation of the standard "real time audio and video service (RTC) basic capability requirements and evaluation methods" issued by the Chinese Academy of Communica

SD_ DATA_ RECEIVE_ SHIFT_ REGISTER
随机推荐
Borui data was selected in the 2022 love analysis - Panoramic report of it operation and maintenance manufacturers
Make insurance more "safe"! Kirin Xin'an one cloud multi-core cloud desktop won the bid of China Life Insurance, helping the innovation and development of financial and insurance information technolog
SlashData开发者工具榜首等你而定!!!
Classification and application of enterprise MES Manufacturing Execution System
【MIME笔记】
POJ 1182 :食物链(并查集)[通俗易懂]
testing and SQA_ Dynamic white box test [easy to understand]
Number - number (Lua)
基于图像和激光的多模态点云融合与视觉定位
Business experience in virtual digital human
In the first half of 2022, I found 10 books that have been passed around by my circle of friends
炒股如何开户?请问一下手机开户股票开户安全吗?
How to open an account for stock speculation? Excuse me, is it safe to open a stock account by mobile phone?
LeetCode 497(C#)
Teach your sister to write the message queue hand in hand
A hodgepodge of ICER knowledge points (attached with a large number of topics, which are constantly being updated)
Hutool - lightweight DB operation solution
Short selling, overprinting and stock keeping, Oriental selection actually sold 2.66 million books in Tiktok in one month
AI writes a poem
国内首次!这家中国企业的语言AI实力被公认全球No.2!仅次于谷歌