I am trying to use template/string literals for templates, I've been watching several videos about the subject and been following this great tutorial.
I thought it would be quite cool with reusable chunks because some of the elements occur several times.
Template function
function templater(strings, ...keys) {
return function(data) {
let temp = strings.slice();
keys.forEach((key, i) => {
temp[i] = temp[i] + data[key];
});
return temp.join('');
}
};
Example chunks
let contentHead = `
<header>
${'myHeader'}
</header>
`
let contentFooter = `
<footer>
${'myFooter'}
</footer>
`
The template which is being packed with all the necessary chucks
let contentTemplate = templater`
<div>
${'contentHead'}
${'contentFooter'}
</div>
`
This is where I set the data for the template
const content = {
myHeader: 'This is my header',
myFooter: 'This is my footer',
contentHead: contentHead,
contentFooter: contentFooter,
}
This is how I test the code
const myTemplate = contentTemplate(content);
console.log(myTemplate);
The output will be
<div>
<header>
myHeader
</header>
<footer>
myFooter
</footer>
</div>
If i do it without calling the variables like this
let contentTemplate = templater`
<div>
<header>
${'myHeader'}
</header>
<footer>
${'myFooter'}
</footer>
</div>
const content = {
myHeader: 'This is my header',
myFooter: 'This is my footer'
}
The output will be correct
<div>
<header>
This is my header
</header>
<footer>
This is my footer
</footer>
</div>
So why does this not work, I call in two string literal variables in the JSON Object which is then used in the templater function, does it not work because the two chunks are passed in outside the tagged template function and then switched into the template without its own content being done anything with?
How can I fix this the best possible way? :)