I'm experimenting with HTML String template literals (Electron which uses NodeJS).
It works well but it looks like a mess. What I miss is the separation between HTML and logic.
Here is what I've got
module.exports = {
snippet: (value1, value2) => {
return `
<div>
<h1>Hello ${value1 + ' - ' + value2}</h1>
</div>
`;
},
};
Suggested output
What I wish I could do is like below (which does not work):
module.exports = {
snippet: (value1, value2) => {
return require('snippet.html')(value1, value2);
},
};
<div>
<h1>Hello ${value1 + ' - ' + value2}</h1>
</div>
Why it does not work
A string is flat and can't take arguments
I could get the HTML from the HTML file as a String. The problem is that it will be "flat" and I can't use the logic inside the template literals anymore.
Eval is evil and slow
I've read it's possible to run HTML as a String through eval to make it work again. I've also read that it's not good for security and that it's slow.
Other notes
- I use nodeJS so I need to use
module.exportsin the js file. - I use nested snippets so it's important that template literals still work as it should. It should be able to take variables, functions and so on.
- I don't mind new ES6 syntax.
- I'm aware of Vue, React and other frameworks. I want to keep it small and without the hassle to setup a server this time.
Update - A tiny bit better, but not enough
I've now split logic from the template. Still, both are in the same file which makes the html less readable.
module.exports = {
snippet: (value1, value2) => {
/* Possible to put whatever logic in here */
return html(value1, value2);
},
};
function html(value1, value2) {
return `
<div>
<h1>Hello ${value1 + ' - ' + value2}</h1>
</div>
`;
}