-
Notifications
You must be signed in to change notification settings - Fork 274
Home
You can get Twig.js by either of the following methods:
-
Clone the repository
git clone git://github.com/justjohn/twig.js.git
See the implementation details wiki page for a list of supported filters/functions/tags/tests.
Twig.js is available as a Node package which you can install from npm
npm install twig
Twig.js is compatible with Express 2 and 3 and can be setup with the following code:
Express 3
var Twig = require("twig"),
express = require('express'),
app = express();
// This section is optional and used to configure twig.
app.set("twig options", {
strict_variables: false
});
app.get('/', function(req, res){
res.render('index.twig', {
message : "Hello World"
});
});
app.listen(9999);
Express 2
var twig = require("twig"),
app = require('express').createServer();
app.configure(function () {
app.set('view engine', 'twig');
app.set("view options", { layout: false });
});
app.register('twig', twig);
app.get('/', function(req, res){
res.render('index', {
message : "Hello World"
});
});
app.listen(9999);
Message of the moment: <b>{{ message }}</b>
From the browser, Twig.js can be used with inline templates or templates loaded from AJAX.
var template = twig({
id: "list", // id is optional, but useful for referencing the template later
data: "{% for value in list %}{{ value }}, {% endfor %}"
});
var output = template.render({
list: ["one", "two", "three"]
});
// output = "one, two, three, "
If an id is provided when you create a template, you can reference the template anywhere else in your application by using the ref parameter:
// Elsewhere in your application
var output = twig({ ref: "list" }).render({
list: ["a", "b", "c"]
});
// output = "a, b, c, "
Templates can also be loaded via ajax by setting the href parameter in the twig() options.
templates/posts.twig
{% for post in posts %}
<article>
<header>
<h1>{{ post.title }}</h1>
</header>
<p>{{ post.body }}</p>
</article>
{% endfor %}
app.js
var template = twig({
id: "posts",
href: "templates/posts.twig",
// for this example we'll block until the template is loaded
async: false
// The default is to load asynchronously, and call the load function
// when the template is loaded.
// load: function(template) { }
});
Once you've loaded templates, you can access them via their id and render them when you have data.
posts = { ... }; // data from somewhere like an AJAX callback
// render the template
var postsHTML = twig({ ref: "posts" }).render(posts);
// Display the rendered template
document.getElementById("posts").innerHTML = postsHTML;