Right now, I have an ASP.NET application where, within the aspx files, at various points, I call a function which inserts standard template HTML. For example:
<html>
<head>
</head>
<body>
<%=SectionHeader('Section title 1') %>
some content for section 1
<%=SectionHeader('Section title 2') %>
some content for section 2
</body>
</html>
So wherever the SectionHeader function was called, it would read the passed in parameter, and insert the HTML for the section header, such as {title}. I'm trying to figure out how to accomplish the same thing in Node.
I understand how to do a basic token replacement - reading a static HTML file, looking for a token (such as {token1}) and replacing it with something. But short of using Regex and complex string manipulation, is there any way to accomplish the same thing in Node that I'm doing with ASP.NET?
There are lots of templating engines for node, maybe you should try one of these. If you are searching for a web application framework express would be a good starting point, which has support for many templating enignes.
Of course you could do just string replacement, but a templating engine provides much more.
I took the generated application skeleton, and modified the index.js and index.jade to pass a function into the template. I think is what you are asking for, but there may be opinions if this is a good architecture to have the template call back into logic.
index.js
exports.index = function(req, res){
var fn = function(initial) {
return initial + ". Tester";
};
res.render('index', { title: 'Express', fn : fn });
};
index.jade
block content
h1= title
p Welcome to #{title}
div Hello #{fn('A')}
Now, when I load http://localhost:3000/, this is what renders on the screen. Notice the "A" is being passed into the function to generate the string "A. Tester" for the output.
Express
Welcome to Express
Hello A. Tester