Last active
April 26, 2024 08:13
-
-
Save abbotto/90b3c4391fca37795fb7 to your computer and use it in GitHub Desktop.
A templating solution implemented in JavaScript [207 bytes minified+gzipped]
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
// Author: Jared Abbott | |
// Created: December 2015 | |
// License: MIT | |
var template = function(tpl, data) { | |
// Make sure the cache is available | |
var w = window; | |
w.tplCache = !w.tplCache ? {} : w.tplCache; | |
// Prepare and load the template | |
tpl = ('"' + tpl.replace(/\{\{(.*?)\}\}/g, '"+$1+"') + '"').split(/\'+ | + \'/); | |
// Generate a function that will serve as a template | |
// Introduce the data as local variables using with(){} | |
var fn = (!w.tplCache[tpl]) ? new Function("obj", "with(obj){ var tpl = " + tpl + "} return tpl;")(data) : w.tplCache[tpl]; | |
return fn; | |
}; | |
// EXAMPLE | |
var data = { | |
name: "Mr. Abbotto", | |
profile: { | |
age: 969 | |
}, | |
food: { | |
favourite: 'Cheezbergurz' | |
} | |
} | |
var tpl='<h1>My name is {{ name }}, and I am {{ profile.age }} years old. My favourite food is {{ food.favourite }}.</h1>'; | |
console.log(template(tpl, data)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment