How to include Handlebars partial in a string? (add it to the innerHTML of a DOM Element)

Viewed 18

Is there a way to get the "string version" of a handlebars partial to include it in the innerHTML of an HTML element?

For instance, imagine I have a ToDo list, and I want to add a task everytime I click the button "Add Task", like this:

todo_list.hbs

<div id="todo-list">

</div>
<button onclick="addTask">Add Task</button>

And that I have a handlebars partial in the file "task.hbs":

task.hbs

<h1>The task is: {{title}}</h1>

My question is: How could I create a Task partial everytime the button "Add Task" is clicked? Something like this:

<div id="todo-list">

</div>
<button onclick="addTask">Add Task</button>
<script>
function addTask() {
    const todo_list = document.getElementById('todo_list');
    todo_list.innerHTML += {{> Task title="A new task"}};
    // More code here...
}
</script>

I have also tried enclosing the partial with backticks (`{{> Task title="A new task"}}`), and quotes ("{{> Task title='A new task'}}") as well as read many posts on this subject, but all of them use handlebars.js, not express-handlebars.

I am using express.js for the backend, and therefore, express-handlebars as the view engine. In advance, thanks a lot for your help!

1 Answers

You are very close to getting this to work.

As you have noted, your Handlebars is executing on the server-side. In the case of your partial, you are trying to have it render within a script block. In order for the result to be valid JavaScript, you would need have quotes around the output of the partial so that it will be a valid JavaScript string. Therefore:

todo_list.innerHTML += "{{>Task title='A new task'}}";

Which, when rendered, would result in:

todo_list.innerHTML += "<h1>The task is: A new task</h1>";

It should be noted that quotes in your partial could be problematic. For example, if the <h1> in your partial had a class <h1 class="task">, the resultant JavaScript would now be invalid because the quote after the = would be interpreted as the closing quote of the JavaScript string. Therefore, you would need to be sure to either escape the quotes in your partial or ensure they are different from those used to wrap your partial call (a single-quote ('), in this case.

todo_list.innerHTML += "<h1 class=\"task\">The task is: A new task</h1>";

Additionally, you have an inconsistency with the id of your <div>. The tag has id="todo-list" (with a dash); but your JavaScript has document.getElementById('todo_list') (with an underscore). Those will need to be consistent.

Related