Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Template Engine
export const template = function (tpl, data) {
if (typeof tpl !== 'string') return ''
if (typeof data !== 'object') return tpl
const interpolate = new RegExp('{{(.+?)}}', 'gi')
let result = tpl
result = result.replace(interpolate, (...args) => {
const values = args[1] ? args[1].trim().split('||') : ''
let result = undefined
values.forEach((v) => {
if (result !== undefined) return result
const ks = v.trim().split('.')
result = ks.reduce((acc, cur) => {
return acc ? acc[cur] : undefined
}, data)
})
return result || ''
})
return result
}
template('Hello {{ name || fullname || surname }} and {{ data.another.name }}', {
fullname: 'Ricardo Canelas',
})
export const template = function (tpl, data) {
let result = tpl
const interpolate = {
expression: new RegExp('{{!(.+?)}}', 'gi'),
default: new RegExp('{{(.+?)}}', 'gi'),
}
result = result.replace(interpolate.expression, function (...args) {
const expression = args[1] ? args[1] : ''
const code = `"use strict";${Object.keys(data)
.map((key) => {
return `const ${key} = ${JSON.stringify(data[key], null, 2)};`
})
.join('\n')}
try {
return (${expression})
} catch (error) {
conosle.log('error:')
conosle.log(error)
return ''
}`
const value = Function(code)()
return value || ''
})
result = result.replace(interpolate.default, (...args) => {
const keys = args[1] ? args[1].trim().split('.') : ''
const value = keys.reduce((acc, cur) => {
return acc ? acc[cur] : undefined
}, data)
return value || ''
})
return result
}
template('Hello {{ data.name }} {{! 1 + 2 }}', { data: { name: 'Rico' } })
@ricardocanelas

This comment has been minimized.

@ricardocanelas

This comment has been minimized.

Copy link
Owner Author

@ricardocanelas ricardocanelas commented Oct 28, 2020

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment