【Node中间层实践(三)】----模板引擎pug

前言:
    本文是学习Node中间层实践的相关笔记,推荐大家可以去阅读Keyon Y大佬的原文Node中间层实践 。开启本文前,也可以先去阅读以下,Node中间层实践(一)——基于NodeJS的全栈式开发Node中间层实践(二)——搭建项目框架Node中间层实践(三)——webpack配置,对了解本文内容有所帮助。(PS:继续还债的node小白╮(╯▽╰)╭)

一、pug介绍

pug是一个很简洁很灵活的模板引擎。配合express使用时,在启动文件(app.js)中配置。

// 设置模板类型
app.set('view engine', 'pug');
// 设置模板文件路径
app.set('views', path.resolve(__dirname, 'src/Views'));

即可使用。

二、pug的继承

extends和block实现了pug的继承。
把html中公共/重复的部分提出,写在如layout.pug中

// Shared/layout.pug
doctype html
html
    head
        meta(charset="UTF-8")
        title #{
    
    title}
        meta(name="keywords" content=keywords)
        meta(name="description" content=description)
        meta(http-equiv="X-UA-Compatible" content="IE=edge,chrome=1")
        meta(name="renderer" content="webkit")
        link(rel='stylesheet' href='/Contents/base.css')    //- 公用样式
        block links
        script(type='text/javascript', src='/assets/jquery-1.10.2.min.js')
    body
        include header

        block content

        include footer

        include ../Include/toplink

        block scripts
        script(type='text/javascript', src='/Scripts/base.js')  //- 公用js
        block javascript

// Home/index.pug
extends ../Shared/layout

block links
    link(rel='stylesheet' href='/Contents/index.css')
block scripts
    script(type='text/javascript', src='/Scripts/index.js')

block content
    include ../Include/homeInclude
    
    .container
    .clear

三、Mixin----对html进行函数式编程

pug通过mixin便可以实现对html的函数式编程

//- include/homeInclude.pug
mixin homeBtnBox(num)
    //- num:  0-报名中  1-已结束
    .hr_btnBox
        a(href="/User" + targetId + "/Mas" class=num == 0 ? "active" : "") 报名中
        a(href="/User" + targetId + "/Mas/Require/Finish" class=num == 1 ? "active" : "") 已结束
        
//- home/home.pug
include ../include/homeInclude  //- 引入编写mixin的pug文件
+homeBtnBox(1)       //- 传参调用

判断并绑定多个classname的方法

.btn(class={
    
    "btn_t1": item.status == 0, "btn_t2": item.status == 1, "btn_t3": item.status == 2})

用过ng、vue的同学都熟悉这种方式,在pug中也可以这样使用,但是只有class的属性可以使用这种判断方式,其他的属性,href、title、value等等都不可以这么用。

四、逻辑运算后再绑定数据的方法

有时候,从后端返回的数据需要进行处理,才可以使用,可以在node中间层里编写数据处理的方法,运算后再返回,或者,也可以试试如下的方法:pug的通过一个–表示一段不输出的代码,提供一个js语法执行环境,运算js后再将运算结果绑定到pug模板中

参考博客:

Node中间层实践(四)——模板引擎pug https://juejin.cn/post/6844904191610060808

猜你喜欢

转载自blog.csdn.net/qq_26780317/article/details/125847906