I'm new to node and have been trying to find a way to integrate mustache in a way thats flexible for how I build templates. After trying hogan, mustache-express and the other permutations of mustache, I found the following to make sense to me.
Im not sure if there is a more efficient way of handling this. Basically I like to have control of partial templates so I can load them in module positions on a master template. So this is the basic setup
I have 3 partial templates and one wrapper/master template, the following values are just for example.
./views/wrapper.tpl
<html>
<title>{{ title }}</title>
<body>
<h1>{{ heading }}</h1>
<div>{{> position_1 }}</div>
<div>{{> position_2 }}</div>
<div>{{> position_3 }}</div>
</body>
</html>
./views/module_1.tpl
<h2>{{module_1.title}}</h2>
<p>{{module_1.body}}</p>
./views/module_2.tpl
<h2>{{module_2.title}}</h2>
<p>{{module_2.body}}</p>
./views/module_3.tpl
<h2>{{module_3.title}}</h2>
<p>{{module_3.body}}</p>
Im using Express but removed the default jade render engine. I only included the code that needs to be added to a default express install. mustache and fs are needed
.
.
.
var mustache = require('mustache');
var fs = require('fs');
.
.
.
app.get('/', function(req, res){
// grab master template
var wrapper = fs.readFileSync('./views/wrapper.tpl', "utf8");
// load data that will be used in template & partials
var data = {
'title': 'dashboard',
'heading': 'welcome to your dashboard',
'module_1':{
'title': 'module 1 title',
'body': 'module 1 body'},
'module_2':{
'title': 'module 2 title',
'body': 'module 2 body'},
'module_3':{
'title': 'module 3 title',
'body': 'module 3 body'}};
// load partial templates
var partials = {'position_1': fs.readFileSync('./views/module_1.tpl', "utf8"),
'position_2': fs.readFileSync('./views/module_2.tpl', "utf8"),
'position_3': fs.readFileSync('./views/module_3.tpl', "utf8")}
// include partials and then replace variables with given data
var html = mustache.to_html(wrapper, data, partials);
// send output to browser
res.send(html);
});
.
.
.
.
This to me makes alot more sense then other examples I have seen, and it works well with mustache. I am able to give the user custom control as to where they want the modules to be positioned. So my questions are
Is there a more efficient way of doing this?
Is there anything wrong with the way Im going about this?
By bypassing Express rendering capabilities what am I missing out?
Why should I use libraries like consolidate and add another layer to express?
Thanks!
If you don't want express rendering, thats fine in my book, I even removed the whole module in some of my lab projects just to get a better understanding of routing in node. However I'd really advice against using readFileSync since It's a blocking method and will make concurency a problem, always use readFile so you get that async callback.