I have a code like res.sendfile('./home.html',{user:req.user}) and I want to access the user parameter in the HTML file. I don't want to use a template engine. How do I do this?
-
You're asking on how to create a template engine, while saying you don't want to use one. Dependencies aren't bad things.Brendan– Brendan2014-12-09 04:35:04 +00:00Commented Dec 9, 2014 at 4:35
Add a comment
|
1 Answer
If you don't want to use a template engine, you manually need to read in the file, then push whatever value you want into a placeholder...
var fs = require('fs');
...
fs.readFile('./home.html', {encoding:'utf8'}, function(err, file){
if (err) return res.end('ERROR');
file = file.replace('%USER%', req.user);
res.end(file);
});
What you are describing is precisely what templates are for... now, if you want these variables to be available in JS.. then you may want a client "var cfg = %%CLIENT_CONFIG%%;" somewhere at the top, and you can JSON.stringify your config, and do the same replace.
If you want a lightweight templating engine you can use manually, you probably want to use lodash's template method.
2 Comments
Akash Babu
but what is %USER% here? I'm getting an error like has no method replace
Ninad
%USER% is placeholder you want to replace