Last active
October 28, 2020 17:54
-
-
Save ricardocanelas/560bc806f34b40cedc4ec7ccf43b3b3b to your computer and use it in GitHub Desktop.
Template Engine
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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', | |
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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' } }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
more info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval