I would like to be able to insert a comma inside handlabars.js, for example: {{ JOURNAL \, }} rendering a comma for each item that exists, so there won't be nonsense commas due to a non existing key-value pair. Thank you all!
{{#each items}}
<button class="accordion-button"
{{#if (equals type "article")}} {{AUTHOR}} {{TITLE}} {{JOURNAL}}, {{VOLUME}}({{NUMBER}}) {{MONTH}} {{YEAR}} {{/if}}
</button>
{{/each}}
CodePudding user response:
You can check if JOURNAL
exists. Then include it and a trailing comma only if it does.
{{#if JOURNAL}}{{JOURNAL}}, {{/if}}
You can also create your own custom helper:
Handlebars.registerHelper('ifExistAddComma', function (str) {
return str === undefined ? '' : `${str}, `;
})
{{ifExistAddComma JOURNAL}}
See playground
Edit: You can write a more complex (but also more general) custom helper for joining any number of arguments with a custom deliminator:
Handlebars.registerHelper('join', function (delim, ...args) {
args.pop() // remove meta information
return args
.filter(arg => arg !== undefined) // filter out undefined properties
.join(delim);
})
{{join ', ' AUTHOR TITLE JOURNAL (join '' VOLUME '(' NUMBER ')') MONTH YEAR}}
author, title, journal, volume(number), month, year