///
namespace Leaf {
let reg = /{{([a-zA-Z0-9]+)(:[^}]*)?}}/g
export type StringFunction = (name: string) => string
export function renderString(str: string, actions: {
[index: string]: string | StringFunction
}): string {
reg.lastIndex = 0
return str.replace(reg, (match, name: string, content: string) => {
if (content) {
content = content.slice(1) || null
}
if (typeof actions[name] === "function") {
let fn: StringFunction = actions[name] as StringFunction
return fn[name](content)
} else if (typeof actions[name] === "string" || typeof actions[name] === "number") {
return actions[name].toString()
} else {
return match
}
})
}
export function render(obj: T, actions: {
[index: string]: string | StringFunction
}): T {
if (typeof obj === "string") {
return renderString(obj, actions) as any as T
} else if (obj instanceof String) {
return renderString(obj.toString(), actions) as any as T
} else if (!obj) {
return obj
} else if (Array.isArray(obj)) {
return obj.map((item) => {
return render(item, actions)
}) as any as T
} else if (obj instanceof Date) {
return obj as any as T
} else if (typeof obj === "object") {
let result: any = {}
for (let key in obj) {
let value = render(obj[key], actions)
result[key] = value
}
return result as any as T
}
return obj
}
}