Skip to content

Instantly share code, notes, and snippets.

@scriptype
Created April 19, 2017 13:58
Show Gist options
  • Save scriptype/e81ec9f5f7a1f33c42c7f0a4709a7646 to your computer and use it in GitHub Desktop.
Save scriptype/e81ec9f5f7a1f33c42c7f0a4709a7646 to your computer and use it in GitHub Desktop.
A very dummy template engine
(function() {
function engine(template, data) {
(template.match(/{\{(.+)\}\}/g) || []).forEach(variable => {
var pureVar = variable.replace(/(\{|\})/g, '')
var innerAccess = pureVar.split(/\./)
var finalValue = innerAccess.reduce((acc, curr) => acc[curr], data)
template = template.replace(variable, finalValue)
})
return template
}
var input = `
<h1>{{title}}</h1>
<div>
<p>{{content}}</p>
<p>title's length: {{title.length}}</p>
</div>
`
var output = engine(input, {
title: 'Hello',
content: 'Lorem ipsum dolor sit amet'
})
console.log(output)
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment