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