Reputation: 135
In my js file, I pass a JSON object with two keys - {'tests': tests, 'isComplete': isComplete}
In my handlebars file, I want to display the tests object based on each test status. At the same time, there's another condition for which I added a helper named 'isRequired' that I want to check the test against only if isComplete is not true.
{{#if isComplete}}
{{#each tests}}
{{#isRequired this}}
// display data
{{/isRequired}}
{{/each}}
{{else}}
{{#each tests}}
// display data
{{/each}}{{/if}}
This code has the duplicate code to display data. I'm still learning handlebars and not sure how to eliminate this redundant code block. Can you help me how I can refactor this? Thank you!
Upvotes: 0
Views: 713
Reputation: 9003
I would probably solve this by adding an isComplete
parameter to your isRequired
helper. You have not provided the code for your helper, but I imagine it would end up looking something like this:
Handlebars.registerHelper('isRequired', function (context, isComplete, options) {
if (!isComplete) { return options.fn(context); }
/* rest of isRequired implementation here */
});
Your template would then be updated as follows:
{{#each tests}}
{{#isRequired this ../isComplete}}
// display data
{{/isRequired}}
{{/each}}
Note that this implementation applies the isRequired
logic only if isComplete
is true
. This is the same rules as exist in your template code sample. However, these rules appear to contradict the text of your question, which specifies that isRequired
should be applied "only if isComplete is not true". If these are the requirements we must meet, we need only remove the not operator from our new guard clause:
if (isComplete) { return options.fn(context); }
Upvotes: 1