budibase/packages/string-templates/src/helpers/index.js

67 lines
1.7 KiB
JavaScript
Raw Normal View History

const Helper = require("./Helper")
const { SafeString } = require("handlebars")
const externalHandlebars = require("./external")
2021-01-26 13:43:26 +01:00
const {
HelperFunctionNames,
HelperFunctionBuiltin,
LITERAL_MARKER,
} = require("./constants")
const HTML_SWAPS = {
"<": "&lt;",
">": "&gt;",
}
const HELPERS = [
// external helpers
2021-05-04 12:32:22 +02:00
new Helper(HelperFunctionNames.OBJECT, value => {
return new SafeString(JSON.stringify(value))
}),
// this help is applied to all statements
2021-05-04 12:32:22 +02:00
new Helper(HelperFunctionNames.ALL, value => {
// null/undefined values produce bad results
if (value == null || typeof value !== "string") {
return value || ""
}
if (value && value.string) {
value = value.string
}
let text = new SafeString(value.replace(/&amp;/g, "&"))
if (text == null || typeof text !== "string") {
return text
}
2021-05-04 12:32:22 +02:00
return text.replace(/[<>]/g, tag => {
return HTML_SWAPS[tag] || tag
})
2021-01-21 12:32:26 +01:00
}),
// adds a note for post-processor
2021-05-04 12:32:22 +02:00
new Helper(HelperFunctionNames.LITERAL, value => {
2021-01-26 13:43:26 +01:00
const type = typeof value
const outputVal = type === "object" ? JSON.stringify(value) : value
return `{{${LITERAL_MARKER} ${type}-${outputVal}}}`
2021-01-26 13:43:26 +01:00
}),
]
module.exports.HelperNames = () => {
return Object.values(HelperFunctionNames).concat(
HelperFunctionBuiltin,
2021-01-21 18:30:51 +01:00
externalHandlebars.externalHelperNames
)
}
2021-05-04 12:32:22 +02:00
module.exports.registerAll = handlebars => {
for (let helper of HELPERS) {
helper.register(handlebars)
}
// register imported helpers
externalHandlebars.registerAll(handlebars)
}
2021-05-04 12:32:22 +02:00
module.exports.unregisterAll = handlebars => {
for (let helper of HELPERS) {
helper.unregister(handlebars)
}
// unregister all imported helpers
externalHandlebars.unregisterAll(handlebars)
}