budibase/packages/string-templates/src/helpers/Helper.ts

37 lines
938 B
TypeScript
Raw Normal View History

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) {
this.name = name
this.fn = fn
this.useValueFallback = useValueFallback
}
2024-02-22 11:52:50 +01:00
register(handlebars: typeof Handlebars) {
// 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
}
}
2024-02-22 11:52:50 +01:00
)
}
2024-02-22 11:52:50 +01:00
unregister(handlebars: { unregisterHelper: any }) {
handlebars.unregisterHelper(this.name)
}
}