node.js中EJS 模板快速入门教程
Node开源模板的选择很多,但推荐像我这样的老人去用EJS,有ClassicASP/PHP/JSP的经验用起EJS来的确可以很自然,也就是说,你能够在<%...%>块中安排JavaScript代码,利用最传统的方式<%=输出变量%>(另外<%-输出变量是不会对&等符号进行转义的)。安装EJS命令如下:
npminstallejs
JS调用
JS调用的方法主要有两个:
ejs.compile(str,options); //=>Function ejs.render(str,options); //=>str
实际上EJS可以游离于Express独立使用的,例如:
varejs=require(''),str=require('fs').readFileSync(__dirname+'/list.ejs','utf8'); varret=ejs.render(str,{ names:['foo','bar','baz'] }); console.log(ret);
见ejs.render(),第一个参数是模板的字符串,模板如下。
<%if(names.length){%>
-
<%names.forEach(function(name){%>
names成了本地变量。
选项参数
第二个参数是数据,一般是一个对象。而这个对象又可以视作为选项,也就是说数据和选择都在同一个对象身上。
如果不想每次都都磁盘,可需要缓存模板,设定options.filename 即可。例如:
varejs=require('../') ,fs=require('fs') ,path=__dirname+'/functions.ejs' ,str=fs.readFileSync(path,'utf8'); varusers=[]; users.push({name:'Tobi',age:2,species:'ferret'}) users.push({name:'Loki',age:2,species:'ferret'}) users.push({name:'Jane',age:6,species:'ferret'}) varret=ejs.render(str,{ users:users, filename:path }); console.log(ret);
相关选项如下:
- cacheCompiledfunctionsarecached,requiresfilename
- filename缓存的键名称
- scope函数执行的作用域
- debugOutputgeneratedfunctionbody
- compileDebugWhenfalsenodebuginstrumentationiscompiled
- clientReturnsstandalonecompiledfunction
inculde指令
而且,如果要如
-
<%users.forEach(function(user){%>
<%includeuser/show%>
<%})%>
一般插入公共模板,也就是引入文件,必须要设置filename选项才能启动include特性,不然include无从知晓所在目录。
模板:
Users
<%functionuser(user){%>
-
<%users.map(user)%>
EJS支持编译模板。经过模板编译后就没有IO操作,会非常快,而且可以公用本地变量。下面例子user/show忽略ejs扩展名:
-
<%users.forEach(function(user){%>
<%includeuser/show%>
<%})%>
自定义CLOSETOKEN
如果打算使用
{{=title}}
般非<%%>标识,也可以自定义的。varejs=require('ejs'); ejs.open='{{'; ejs.close='}}';
格式化输出也可以哦。
ejs.filters.last=function(obj){ returnobj[obj.length-1]; };
调用
<%=:users|last%>
EJS也支持浏览器环境。
<%if(names.length){%> <%names.forEach(function(name){%>
<%}%>- <%=name%>
<%})%>
不知道EJS能否输出多层JSON对象呢?
对了,有网友爆料说,jQ大神John若干年前写过20行的模板,汗颜,与EJS相似但短小精悍!
简单实用的js模板引擎
不足50行的js模板引擎,支持各种js语法:
<%= for(vari=0,l=p.list.length;i class="first"<%=}=%>><%==stu.name=%> <%==stu.age=%> <%==(stu.address||'')=%> <%= } =%> “<%=xxx=%>”内是js逻辑代码,“<%==xxx=%>”内是直接输出的变量,类似php的echo的作用。“p”是调用下面build方法时的k-v对象参数,也可以在调用“newJTemp”时设置成别的参数名
调用:
$(function(){ vartemp=newJTemp('test_list'), html=temp.build( {list:[ {name:'张三',age:13,address:'北京'}, {name:'李四',age:17,address:'天津'}, {name:'王五',age:13} ]}); $('table').html(html); });上面的temp生成以后,可以多次调用build方法,生成html。以下是模板引擎的代码:
varJTemp=function(){ functionTemp(htmlId,p){ p=p||{};//配置信息,大部分情况可以缺省 this.htmlId=htmlId; this.fun; this.oName=p.oName||'p'; this.TEMP_S=p.tempS||'<%='; this.TEMP_E=p.tempE||'=%>'; this.getFun(); } Temp.prototype={ getFun:function(){ var_=this, str=$('#'+_.htmlId).html(); if(!str)_.err('error:notemp!!'); varstr_='var'+_.oName+'=this,f=\'\';', s=str.indexOf(_.TEMP_S), e=-1, p, sl=_.TEMP_S.length, el=_.TEMP_E.length; for(;s>=0;){ e=str.indexOf(_.TEMP_E); if(e核心是将模板代码转变成了一个拼接字符串的function,每次拿数据call这个function。
因为主要是给手机(webkit)用的,所以没有考虑字符串拼接的效率问题,如果需要给IE使用,最好将字符串拼接方法改为Array.push()的形式。
附:connect+ejs的一个例子。
varStep=require('../../libs/step'), _c=require('./utils/utils'), fs=require('fs'), ejs=require('ejs'), connect=require('connect'); exports.loadSite=function(request,response){ varsiteRoot='C:/代码存档/sites/a.com.cn'; //_c.log(request.headers.host); varurl=request.url; //如果有html的则是动态网页,否则为静态内容 if(url=='/'||~url.indexOf('/?')||url.indexOf('.asp')!=-1||url[url.length-1]=='/'){ vartplPath; if(url=='/'||~url.indexOf('/?')||url[url.length-1]=='/'){ //默认index.html tplPath=siteRoot+request.url+'default.asp'; }else{ tplPath=siteRoot+request.url.replace(/\?.*$/i,'');//只需要文件名 } //从文件加载模板 Step(function(){ _c.log('加载模板:'+tplPath); fs.exists(tplPath,this); },function(path_exists){ if(path_exists===true)fs.readFile(tplPath,"utf8",this); elseif(path_exists===false)response.end404(request.url); elseresponse.end500('文件系统异常',''); },function(err,tpl){ varbigfootUrl,cssUrl,projectState=0;//0=localhot/1=TestServer/2=Deployed switch(projectState){ case0: bigfootUrl="http://127.0.0.1/bigfoot/"; cssUrl="http://127.0.0.1/lessService/?isdebug=true"; break; case1: bigfootUrl="http://112.124.13.85:8080/static/"; cssUrl="/asset/style/"; break; case2: bigfootUrl="http://localhost:8080/bigfoot/"; break; } varsitePath=request.getLevelByUrl(require(siteRoot+'/public/struct')), first=sitePath[0]; varhtmlResult=ejs.render(tpl,{ filename:tplPath, bigfootUrl:bigfootUrl, cssUrl:cssUrl, projectState:projectState, query_request:request.toJSON(), request:request, config:require(siteRoot+'/public/config'), struct:require(siteRoot+'/public/struct'), sitePath:sitePath, firstLevel:first }); //_c.log(first.children.length) response.end200(htmlResult); }); }else{ connect.static(siteRoot)(request,response,function(){ //ifnotfound... response.writeHead(404,{'Content-Type':'text/html'}); response.end('404'); }); } }以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
热门推荐
- 返回顶部
- 3162201930
- czq8825@qq.com