Search code examples
javascripthandlebars.jspartials

How do I reference a Handlebars partial inside of a partial on the client?


Background

I've got two partials, 'Post' and 'Subject'. Posts can have many subjects and I'm trying to create new posts using handlebars. Posts use an each loop to render every subject.

{{#each subjects}}
    {{> subject}}
{{/each}}

Subjects look like this:

<li class="post-subject">{{postSubject}}</li>

Specific Problem

I'm getting the error "The partial subject could not be found" when I pass an object like this:

// Subjects come in this form
let subs = [{"postSubject": "Avengers: Endgame"},
            {"postSubject": "Avengers: Infinity War"}];

let postObj = {
    postContent: "some_string",
    timestamp:   "some_string",
    subjects:    subs
};

to this function:

let newPost = Handlebars.templates.post(postObj);

I'm honestly not sure why it can't find the subjects partial as I can pass the exact same array of objects from my server to the client and it renders them just fine. Of course, passing a [] for the subjects works just fine. All of my partials are stored in the same folder as well.

I assume the templates function lets the client find out where the 'Post' partial is stored, but not where others could be and that's why it can't find the subjects partial, but I honestly don't know.

Feel free to ask any questions if I'm vague in some places/didn't provide enough information. Thank you in advance!


Solution

  • After fiddling around with this for a hot second, I finally found out that I need to register the subject partial using:

    Handlebars.registerPartial('subject', '<li class="post-subject">{{postSubject}}</li>');
    

    I wish I could reference the actual partial in the second element, but I'm not sure how. This works though and that's all I need.