I'm learning how to use templatesjs from: https://www.npmjs.com/package/templatesjs
They have an example of using include html file in other html file (using <%include%>
tag)
When I'm trying to build my own example, it doesn't work (The screen is empty, with no errors):
var express = require('express');
var app = express();
var fs = require('fs');
var bodyParser = require('body-parser');
app.use(bodyParser.json())
var templatesjs = require('templatesjs');
// FILES
var MAIN_FILE = '/main.html';
/*
* Home page
*/
app.get('/', function (req, res) {
fs.readFile(__dirname + MAIN_FILE, function(err,data){
if(err) throw err;
templatesjs.set(data, function(err,data){
if(err) throw err;
res.send();
});
});
})
/*
* Startup
*/
var server = app.listen(8082, function () {
var host = server.address().address
var port = server.address().port
// start
console.log("App listening at http://%s:%s", host, port)
})
the main html.file looks:
<html>
<title> Tutorial -> Templates Js Server </title>
<head>
</head>
<body>
<div>
<%include Top.html%>
</div>
<div>
</div>
</body>
</html>
and Top.html file looks:
<p>TOP</p>
(I have tried to add <html>
tag into Top.html, but same results);
The problem is that the web screen I'm getting is empty (with no errors at Node.js)
What am I doing wrong ?
It's because you doesn't send back any data to incoming request! your res.send()
is empty. you should send something back if you really want to show it. for example: res.send('hello world')
.
If you want to render your template with your data, you could use templatesjs.renderAll()
method to populate your html template with desired data as follows:
// set default directory for html partials
templatesjs.dir = "./public/partials/";
app.get('/', function(req, res) {
fs.readFile(__dirname + MAIN_FILE, function(err, data) {
if (err) throw err;
templatesjs.set(data, function(err, data) {
if (err) throw err;
var list = { // this is your data
name: 'your name'
};
templatesjs.renderAll(list, function(err, data) {
if (err) throw err;
res.send(data);
});
});
});
})
Top.html:
<p>Hello, my name is <%name%></p>
and this file should reside in ./public/partials/
directory as we set default include directory to this path;
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.