Skip to content

Instantly share code, notes, and snippets.

@haochi
Forked from 140bytes/LICENSE.txt
Created July 10, 2011 23:23
Show Gist options
  • Save haochi/1075080 to your computer and use it in GitHub Desktop.
Save haochi/1075080 to your computer and use it in GitHub Desktop.
tofu: tiny templating engine

140byt.es

A tweet-sized, fork-to-play, community-curated collection of JavaScript.

How to play

  1. Click the Fork button above to fork this gist.
  2. Modify all the files to according to the rules below.
  3. Save your entry and tweet it up!

Keep in mind that thanks to the awesome sensibilities of the GitHub team, gists are just repos. So feel free to clone yours and work locally for a more comfortable environment, and to allow commit messages.

Rules

All entries must exist in an index.js file, whose contents are

  1. an assignable, valid Javascript expression that
  2. contains no more than 140 bytes, and
  3. does not leak to the global scope.

All entries must also be licensed under the WTFPL or equally permissive license.

For more information

The 140byt.es site hasn't launched yet, but for now follow @140bytes on Twitter.

To learn about byte-saving hacks for your own code, or to contribute what you've learned, head to the wiki.

140byt.es is brought to you by Jed Schmidt. It was inspired by work from Thomas Fuchs and Dustin Diaz.

function tofu(template, values){
// searches for { variables } inside the template string,
// pass the matched value "match" to the function. ("a" here
// is just a placeholder, it includes the curly braces, while
// "match" is just the variable name we will be using.)
return template.replace(/{ *([\w\.]+) *}/g, function(a, match){
// splits the variable name, so we can access nested object
// using the familiar dot notation.
var levels = match.split("."),
item = values;
// each iteration will move "item" one level closer to the
// actual value we are looking for. For example, if the
// value of "match" is "place.name.translation", before
// the for loop, "item" will be equal to the "values" object.
// After the first iteration "item" will become "values.place",
// after the second it will be "values.place.name", and at
// the last iteration it will be "values.place.name.translation",
// which is what we want.
for(var i=0;i<levels.length;i++){
item = item[levels[i]];
}
// then we return this value and let String.replace do its magic.
return item;
});
}
function tofu(c,e){return c.replace(/{ *([\w\.]+) *}/g,function(c,f){for(var d=f.split("."),a=e,b=0;b<d.length;b++)a=a[d[b]];return a})};
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2011 Haochi Chen <http://ihaochi.com>
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": "tofu",
"description": "Tofu is a logic-less, tweet-size JavaScript templating engine.",
"keywords": [
"tofu",
"template"
]
}
<!DOCTYPE html5>
<html>
<head>
<link rel="stylesheet" href="http://code.jquery.com/qunit/git/qunit.css" type="text/css" media="screen" />
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="http://code.jquery.com/qunit/git/qunit.js"></script>
<script>
function tofu(c,e){return c.replace(/{ *([\w\.]+) *}/g,function(c,f){for(var d=f.split("."),a=e,b=0;b<d.length;b++)a=a[d[b]];return a})};
</script>
<script>
$(document).ready(function(){
test("Simple object test", function() {
equals("I am a Berliner", tofu("{Ich} am {ein} Berliner", {Ich: "I", ein: "a"}));
});
module("Nested object values");
test("Simple test", function() {
var expected_message = "Welcome to Hong Kong! The current temperature is 20 degrees Celcius."
, template = "Welcome to { place.name }! The current temperature is { place.temperature.magnitude } degrees { place.temperature.unit }."
, rendered_message = tofu(template, {
place: {
name: "Hong Kong",
temperature: {
magnitude: 20,
unit : "Celcius"
}
}
});
equals(expected_message, rendered_message);
});
test("Multiple occurances", function(){
var expected_message = "A rose is a rose is a rose"
, rendered_message = tofu("A { flower } is a { flower } is a { flower }", { flower: "rose" });
equals(expected_message, rendered_message);
});
module("Misc.");
test("Make sure the outgoing values are the same as the incoming values", function(){
var expected_message = "What does a cat do? It meows!",
template = "What does a { animal.species.name } do? It { animal.species.action }!",
values = { animal: {
species: {
name: "cat",
action: "meows"
},
some_other_stuff: "should still be here!"
} };
equals(expected_message, tofu(template, values));
equals(template, "What does a { animal.species.name } do? It { animal.species.action }!");
deepEqual(values, { animal: {
species: {
name: "cat",
action: "meows"
},
some_other_stuff: "should still be here!"
} });
});
});
</script>
</head>
<body>
<h1 id="qunit-header">QUnit</h1>
<h2 id="qunit-banner"></h2>
<div id="qunit-testrunner-toolbar"></div>
<h2 id="qunit-userAgent"></h2>
<ol id="qunit-tests"></ol>
<div id="qunit-fixture">test markup, will be hidden</div>
</body>
</html>
@Kambfhase
Copy link

This is so fucking awesome. srsly!

@rudylattae
Copy link

I like the simplicity of Thomas' http://mir.aculo.us/2011/03/09/little-helpers-a-tweet-sized-javascript-templating-engine/

However, I love the utility tofu provides with dot notation support for nested objects. Great work and thanks for the share!

@haochi
Copy link
Author

haochi commented Aug 5, 2011

Thanks! Thomas' code doesn't handle the edge cases where template-like strings are included in the value. For example, t("{dog}", {dog: "{cat}", cat: "meow"}) would return "meow" instead of "{cat}".

@rudylattae
Copy link

rudylattae commented Aug 5, 2011 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment