Created
April 19, 2017 13:58
-
-
Save scriptype/e81ec9f5f7a1f33c42c7f0a4709a7646 to your computer and use it in GitHub Desktop.
A very dummy template engine
This file contains hidden or 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
(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