Logic-less string interpolation and templating that fits in a tweet.
Modified from the code at https://github.com/mozilla/zamboni/blob/master/media/js/zamboni/format.js
Enjoy!
Logic-less string interpolation and templating that fits in a tweet.
Modified from the code at https://github.com/mozilla/zamboni/blob/master/media/js/zamboni/format.js
Enjoy!
| // 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> |