Correctly handle JS nullish values by removing forced fallback value of HBS helper
This commit is contained in:
parent
5691be6fc0
commit
39e98800d3
|
@ -1,14 +1,20 @@
|
||||||
class Helper {
|
class Helper {
|
||||||
constructor(name, fn) {
|
constructor(name, fn, useValueFallback = true) {
|
||||||
this.name = name
|
this.name = name
|
||||||
this.fn = fn
|
this.fn = fn
|
||||||
|
this.useValueFallback = useValueFallback
|
||||||
}
|
}
|
||||||
|
|
||||||
register(handlebars) {
|
register(handlebars) {
|
||||||
// wrap the function so that no helper can cause handlebars to break
|
// wrap the function so that no helper can cause handlebars to break
|
||||||
handlebars.registerHelper(this.name, (value, info) => {
|
handlebars.registerHelper(this.name, (value, info) => {
|
||||||
const context = info?.data?.root
|
const context = info?.data?.root || {}
|
||||||
return this.fn(value, context || {}) || value
|
const result = this.fn(value, context)
|
||||||
|
if (result == null) {
|
||||||
|
return this.useValueFallback ? value : null
|
||||||
|
} else {
|
||||||
|
return result
|
||||||
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -19,7 +19,7 @@ const HELPERS = [
|
||||||
return new SafeString(JSON.stringify(value))
|
return new SafeString(JSON.stringify(value))
|
||||||
}),
|
}),
|
||||||
// javascript helper
|
// javascript helper
|
||||||
new Helper(HelperFunctionNames.JS, processJS),
|
new Helper(HelperFunctionNames.JS, processJS, false),
|
||||||
// this help is applied to all statements
|
// this help is applied to all statements
|
||||||
new Helper(HelperFunctionNames.ALL, value => {
|
new Helper(HelperFunctionNames.ALL, value => {
|
||||||
if (
|
if (
|
||||||
|
|
|
@ -36,11 +36,7 @@ module.exports.processJS = (handlebars, context) => {
|
||||||
|
|
||||||
// Create a sandbox with out context and run the JS
|
// Create a sandbox with out context and run the JS
|
||||||
vm.createContext(sandboxContext)
|
vm.createContext(sandboxContext)
|
||||||
const result = vm.runInNewContext(js, sandboxContext)
|
return vm.runInNewContext(js, sandboxContext)
|
||||||
if (result == null || result === "") {
|
|
||||||
return " "
|
|
||||||
}
|
|
||||||
return result
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
return "Error while executing JS"
|
return "Error while executing JS"
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue