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

Tofu is a logic-less, tweet-size (minified) JavaScript templating engine similar to mustache.js, except that tofu is true logic-less.

Usage

Tofu takes two parameters: a string as template, and a object as values. Variables inside the template are surrounded by a pair of curly braces.

tofu("{ Ich } am { ein } Berliner", { Ich: "I", ein: "a" }); will return I am a Berliner.

You can use access nested object values through the familar dot notation that JavaScript uses, so you can do something like

tofu("Welcome to { place.name }! The current temperature is { place.temperature.magnitude } degrees { place.temperature.unit }.", { 
  place: {
    name: "Hong Kong",
    temperature: {
      magnitude: 20,
      unit : "Celcius"
    }
  }
});

and it will return Welcome to Hong Kong! The current temperature is 20 degrees Celcius.

Why should you use Tofu?

Tofu is fast, tiny, and gets the job done if you don't need the fancy conditional and enumerable sectiosn that mustache offers.

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