Reputation: 1123
I'm trying to build a very simple mvc in node js and express js. So far i've managed to show the right html according to the route taken "site/component/view/layout/bla.html"
Now i'm at the part where i have to take the data and put it in the website. I know there are already template engines but I choose to make my own, simple, template engine. So, i took the apropiate html, and parsed it to get the parts where i should replace with the data. I put some start and end custom tags to get the content with regex. I end up with a STRING like this
"for(var i = 0; i< list.length; i++) {
console.log(list[i]);
}"
Well this is from the parsed HTML. In the backend the "list" array will be taken from the model.
My problem is how do i parse that string to do exactly that, or just to put data in the site. I have to put another custom command like "write list[i].name" and parse it in the backend ? How do i know there is a for loop with 3 arguments, or a while loop. And how do i "execute" it ? Not to mention "if" statements.. is there any easy way ?
Upvotes: 0
Views: 734
Reputation: 1499
What you're trying to do is something quite big.
Nocturno has answered a good solution but it's the best answer we can give you about. And here, you will have a solution with no cache who'll take alot of time and ressources to execute.
You don't have any caching system here nor functions/helpers like if()
or foreach()
. I recommend you to have a look to that website who is great to find out a proper template engine.
For example, I'm using Handlebars, and this is how I pass variables from my back-work to view
templateEngines = ["Handlebars", "Jade", "Mustache", "EJS"];
res.render("index", {
list : templateEngine
});
... and the view (/views/index.handlebars/)
<h1>List of template engines I've used in mah life :</h1>
<ul>
{{#each list}}
<li>{{this}}</li>
{{/each}}
</ul>
And it'll give this HTML at access:
<h1>List of template engines I've used in mah life :</h1>
<ul>
<li>Handlebars</li>
<li>Jade</li>
<li>Mustache</li>
<li>EJS</li>
</ul>
I understand your desire to recreate the hot water but trust me, you'll get something disappointing at the end. Do it when you're sure to bring something better to the Node.JS community otherwise, spend more time on your REST tutorial. Friendly advice!
Upvotes: 2
Reputation: 10027
If I understand you correctly, what you want to do is load up your html into a string, and then replace parts of it with your data before sending it back to the client?
Upvotes: 0