I have use-case as below where I am populating the innerHTML
as below. Now the trouble is I want to resolve the template literal inside the context of forloop. Any clues ?
var blog_entries_dom = 'blog_entries';
var blog_entries = [
{
"title": "Hello World",
"id": 2,
"body": "<p>Hello World</p>"
},
{
"title": "World Hello",
"id": 3,
"body": "<p>World Hello</p>"
}
];
var blog_entry_template = `<div class="post-preview">
<a href="post.html">
<h2 class="post-title">
${item.title}
</h2>
<h3 class="post-subtitle">
${item.body}
</h3>
</a>
<p class="post-meta">Posted by <a href="#">Start Bootstrap</a> #Created At </p>
</div>
<hr>`;
var populate_children = function (element_id, objects_list, template) {
var element = document.getElementById(element_id);
var html = '';
for (var i = 0; i < list.length; i++) {
var item = list[i]
html += template;
}
element.innerHTML = html;
};
populate_children(blog_entries_dom, blog_entries, blog_entry_template);
Template literals are exactly that: Literals. They're evaluated as of where they appear, like all literals. They aren't objects, you can't pass them around.
What you can do instead is put them inside a function and pass the function around. Have the function accept the things the template needs, and return the result of evaluating it.
In your case, you just change
blog_entry_template
to an arrow function, and call it:Usage: