2024-03-19 18:47:39 +01:00
|
|
|
import Handlebars from "handlebars"
|
|
|
|
|
2024-02-21 19:40:50 +01:00
|
|
|
export default class Helper {
|
2024-02-22 11:52:50 +01:00
|
|
|
private name: any
|
|
|
|
private fn: any
|
|
|
|
private useValueFallback: boolean
|
2024-02-21 21:10:53 +01:00
|
|
|
|
2024-02-22 11:52:50 +01:00
|
|
|
constructor(name: string, fn: any, 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
|
|
|
}
|
|
|
|
|
2024-02-22 11:52:50 +01:00
|
|
|
register(handlebars: typeof Handlebars) {
|
2021-01-18 18:40:19 +01:00
|
|
|
// wrap the function so that no helper can cause handlebars to break
|
2024-02-22 11:52:50 +01:00
|
|
|
handlebars.registerHelper(
|
|
|
|
this.name,
|
|
|
|
(value: any, info: { data: { root: {} } }) => {
|
|
|
|
let context = {}
|
|
|
|
if (info && info.data && info.data.root) {
|
|
|
|
context = info.data.root
|
|
|
|
}
|
|
|
|
const result = this.fn(value, context)
|
|
|
|
if (result == null) {
|
|
|
|
return this.useValueFallback ? value : null
|
|
|
|
} else {
|
|
|
|
return result
|
|
|
|
}
|
2021-10-14 14:04:57 +02:00
|
|
|
}
|
2024-02-22 11:52:50 +01:00
|
|
|
)
|
2021-01-18 18:40:19 +01:00
|
|
|
}
|
|
|
|
|
2024-02-22 11:52:50 +01:00
|
|
|
unregister(handlebars: { unregisterHelper: any }) {
|
2021-01-18 18:40:19 +01:00
|
|
|
handlebars.unregisterHelper(this.name)
|
|
|
|
}
|
|
|
|
}
|