2021-01-19 06:40:19 +13:00
|
|
|
class Helper {
|
2021-10-13 03:40:01 +13:00
|
|
|
constructor(name, fn, useValueFallback = true) {
|
2021-01-19 06:40:19 +13:00
|
|
|
this.name = name
|
|
|
|
this.fn = fn
|
2021-10-13 03:40:01 +13:00
|
|
|
this.useValueFallback = useValueFallback
|
2021-01-19 06:40:19 +13:00
|
|
|
}
|
|
|
|
|
|
|
|
register(handlebars) {
|
|
|
|
// wrap the function so that no helper can cause handlebars to break
|
2021-10-12 02:53:55 +13:00
|
|
|
handlebars.registerHelper(this.name, (value, info) => {
|
2021-10-13 03:40:01 +13:00
|
|
|
const context = info?.data?.root || {}
|
|
|
|
const result = this.fn(value, context)
|
|
|
|
if (result == null) {
|
|
|
|
return this.useValueFallback ? value : null
|
|
|
|
} else {
|
|
|
|
return result
|
|
|
|
}
|
2021-01-19 06:40:19 +13:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
unregister(handlebars) {
|
|
|
|
handlebars.unregisterHelper(this.name)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = Helper
|