I need a real jsp-mode template engine, not like jade and ejs:
<%include %>
like jsp (support query params) if more fortune, it would support tile like apache tile. in apache tiles, i can write a template page like
main.jsp:
<%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles" %>
<tiles:insertTemplate template="/layout/simple.jsp">
<tiles:putAttribute name="header" value="/common/header.jsp" />
<tiles:putAttribute name="left" value="/common/leftmenu.jsp" />
<tiles:putAttribute name="body" value="<%= request.getParameter("body")%>" />
<tiles:putAttribute name="footer" value="/common/footer.jsp" />
</tiles:insertTemplate>
now type main.jsp?body=content1.jsp
, you will saw content.jsp appear inside main.jsp, dress layout/simple.jsp.
I can do all above runtime, need not restart webserver.
ejs is probably the closest thing. https://github.com/visionmedia/ejs
./views/account
<% if (user) { %>
<h2><%= user.name %></h2>
<% } %>
./routes/account.js:
res.render('account', { user: user });
I've neerly implement this. lets add something in the ejs example in express. https://github.com/visionmedia/express
modify index.js, first import vm and fs
var express = require('express'),
fs = require('fs'),
vm = require('vm');
then, route all *.shtml (any extension as you will)
app.get('*.shtml', function(req, res){
var url = req._parsedUrl.pathname;
url = url.substring(1, url.length - 6);
//console.log(req);
var jsPath = 'controllers/' + url + '.js';
//console.log('jsPath ' + jsPath);
if(fs.existsSync(jsPath)){
var code = fs.readFileSync(jsPath);
var context = vm.createContext({req : req, res : res, url : url, console : console});
vm.runInContext(code, context, jsPath);
} else {
res.render(url, req.query);
}
});
now, test.
node index.js, now we are in runtime.
put a new file named test.html in views
test.html:
<% include header.html %>
<h1>Test</h1>
<% include footer.html %>
type test.shtml?title=Test Page
, so this page turn to show. and query param title bind within header.html.
well, but we can do less in the page, for the render is controled by the res.render(). if we want to do something before render, or direct output something but not html content, lets have a look.
create a folder named controllers, then create a file named test.js.
test.js
console.log('do something....');
res.render(url, req.query);
type test.shtml?title=Test Page
again, you will see test.js output 'do someting....' on the console, and then it render the same-name page in your browser.
all the controller js and html files are all dynamic~~~
thus the theme mode is not very closely to Apache Tiles yet. :(
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.