Skip to content

Instantly share code, notes, and snippets.

@potch
Forked from 140bytes/LICENSE.txt
Created January 3, 2012 21:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save potch/1557108 to your computer and use it in GitHub Desktop.
Save potch/1557108 to your computer and use it in GitHub Desktop.
zTemplate - a 140byt.es entry for string interpolation
// Basic logic-free string interpolation.
// Usage:
// format('Hello, {name}', {name: 'Bob'});
// > "Hello, Bob"
// format('{0}'s favorite color is {1}.', ['Bob', 'green']);
// > "Bob's favorite color is green."
function format(string, values) {
// Match tokens of the form {foo} or {0}.
var regex = /\{([^}]+)\}/g;
// Replace each matching token {foo} with values['foo'].
return string.replace(regex, function(_, match) {
return values[match];
});
}
// Perform a partial application of the format function.
// Allows for creation of named templates.
// Usage:
// var greeting = template('Hello, {name}');
// greeting({name: 'Bob'});
// > "Hello, Bob"
function template(string) {
return function(values) {
return format(string, values);
}
}
function fmt(s,a,r){r=/\{([^}]+)\}/g;return s.replace(r,function(_,m){return a[m]})};function tmpl(s){return function(a){return fmt(s,a)}}
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2011 YOUR_NAME_HERE <YOUR_URL_HERE>
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
{
"name": "zTemplate",
"description": "This should be a short description of your entry.",
"keywords": [
"template",
"interpolation",
"string"
]
}
<!DOCTYPE html>
<title>zTemplate</title>
<div>Inputs: <code>My name is {name}.</code>, <code>{name: 'Bob'}</code></div>
<div>Expected value: <b>My name is Bob.</b></div>
<div>Actual value: <b id="ret"></b></div>
<script>
// The goods.
function fmt(s,a,r){r=/\{([^}]+)\}/g;return s.replace(r,function(_,m){return a[m]})};function tmpl(s){return function(a){return fmt(s,a)}}
document.getElementById( "ret" ).innerHTML = fmt('My name is {name}', {name: 'Bob'});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment