版权声明:本文首发于本人个人网站KeyonY,转载请注明出处。pug是一个非常简洁灵活的模板引擎。与express一起使用时,在启动文件(app.js)中准备//设置模板类型app.set('viewengine','pug');//设置模板文件路径app.set('views',path.resolve(__dirname,'src/Views'));可以使用。Pug的继承extends和block实现了pug的继承。把html中公共/重新的部分提出来,写在如layout.pug中,//Shared/layout.pugdoctypehtmlhtmlheadmeta(charset="UTF-8")title#{title}meta(name="keywords"content=关键字)元(名称=“描述”内容=描述)元(http-equiv=“X-UA-Compatible”内容=“IE=edge,chrome=1”)元(名称=“渲染器”内容=“webkit")link(rel='stylesheet'href='/Contents/base.css')//-公共样式块链接script(type='text/javascript',src='/assets/jquery-1.10.2.min.js')bodyincludeheaderblockcontentincludefooterinclude../Include/toplinkblockscriptsscript(type='text/javascript',src='/Scripts/base.js')//-公共jsblockjavascript//Home/index.pugextends../Shared/layoutblock链接link(rel='stylesheet'href='/Contents/index.css')blockscriptsscript(type='text/javascript',src='/Scripts/index.js')块内容包括../Include/homeInclude.container.clearMixin—html函数式编程pug可以通过mixin实现html的函数式编程//-include/homeInclude.pugmixinhomeBtnBox(num)//-num:0-registration1-completed.hr_btnBoxa(href="/User"+targetId+"/Mas"class=num==0?"active":"")注册一个(href="/User"+targetId+"/Mas/Require/Finish"class=num==1?"active":"")Ended//-home/home.puginclude../include/homeInclude//-导入编写mixin+homeBtnBox(1)的pug文件//-通过参数调用判断绑定多个类名的方法.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模板。//-时间格式:最多3个月前mixindateFormat(string)-varres='';vartime_zone=newDate().getTime()-newDate(string.replace('T','')).getTime();if(time_zone<0){res='1分钟前'}elseif(time_zone<1*60*60*1000){res=''+Math.floor(time_zone/(1000*60))+'分钟前';}elseif(time_zone<1*24*60*60*1000){res=''+Math.floor(time_zone/(1000*60*60))+'小时前';}elseif(time_zone<1*30*24*60*60*1000){res=''+Math.floor(time_zone/(24*60*60*1000))+'天前';}elseif(time_zone<3*30*24*60*60*1000){res=''+Math.floor(time_zone/(30*24*60*60*1000))+'几个月前';}else{res=''+string.slice(0,10)+'';}span!=res//-!=绑定未转义的代码分享pug中文文档的代码:https://pug.bootcss.com/language/attributes.html欢迎继续关注本系列博文中的其他精彩文章Node中间层实战(一)——全栈开发基于NodeJS的Node中间层实践(二)——搭建项目框架Node中间层实践(三)——webpack配置Node中间层实践(四)——模板引擎pugNode中间层实践(五)——express-logic处理中间层层
