Skip to content

Instantly share code, notes, and snippets.

@ricardocanelas
Last active October 28, 2020 17:54
Show Gist options
  • Save ricardocanelas/560bc806f34b40cedc4ec7ccf43b3b3b to your computer and use it in GitHub Desktop.
Save ricardocanelas/560bc806f34b40cedc4ec7ccf43b3b3b to your computer and use it in GitHub Desktop.
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
Copy link
Author

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