上一篇文章:nodejs微信公众号开发(2)自动回复,实现了简单的关注回复。采用拼接字符串的形式,并不是很方便,这里我们将其封装承接口。
1. ejs模板引擎
不使用拼接字符串的方式,那么模板引擎就是较好的选择。Nodejs开源模板的选择很多,程序中使用
EJS,有
Classic ASP/PHP/JSP的经验用起
EJS来的确可以很自然,也就是说,你能够在
<%...%> 块中安排 JavaScript 代码,利用最传统的方式
<%=输出变量%>(另外 <%-输出变量是不会对 & 等符号进行转义的).2. heredoc
在php、python中都有heredoc方式的字符串定义方法,JavaScript也实现了heredoc模块,主要解决大量字符串拼接问题。
新建模板文件
tpl.js:
'use strict'var ejs = require('ejs');
var heredoc = require('heredoc');
var tpl = heredoc(function(content){/*
<xml>
<ToUserName><![CDATA[<%= toUserName %>]]></ToUserName>
<FromUserName><![CDATA[<%= fromUserName %>]]></FromUserName>
<CreateTime><%= createTime%></CreateTime>
<MsgType><![CDATA[<%= msgType %>]]></MsgType>
<% if(msgType ==='text') { %>
<Content><![CDATA[<%= content %>]]></Content>
<% }else if(msgType ==='image'){ %>
<Image>
<MediaId><![CDATA[<%= content.mediaId %>]]></MediaId>
</Image>
<% }else if(msgType ==='voice'){ %>
<Voice>
<MediaId><![CDATA[<%= content.mediaId %>]]></MediaId>
</Voice>
<% } %>else if(msgType ==='video'){ %>
<Video>
<MediaId><![CDATA[<%= content.mediaId %>]]></MediaId>
<Title><![CDATA[<%= content.title %>]]></Title>
<Description><![CDATA[<%= content.description %>]]></Description>
</Video>
<% } %>else if(msgType ==='music'){ %>
<Music>
<Title><![CDATA[<%= content.title %>]]></Title>
<Description><![CDATA[<%= content.description %>]]></Description>
<MusicUrl><![CDATA[<%= content.musicUrl %>]]></MusicUrl>
<HQMusicUrl><![CDATA[<%= content.hqMusicUrl %>]]></HQMusicUrl>
<ThumbMediaId><![CDATA[<%= content.thumbMediaId %>]]></ThumbMediaId>









