Skip to content

Instantly share code, notes, and snippets.

@redhog
Created March 7, 2012 09:32
Show Gist options
  • Save redhog/1992192 to your computer and use it in GitHub Desktop.
Save redhog/1992192 to your computer and use it in GitHub Desktop.
eejs
<% var e = require("./eejs.js"); e.init(buf); %>
a
<% e.begin_block("bar"); %>
A
<% e.begin_block("foo"); %>
XX
<% e.end_block(); %>
B
<% e.end_block(); %>
b
/* Basic usage:
*
* require("./eejs").require("./foo.ejs")
*/
var ejs = require("ejs");
var fs = require("fs");
exports.init = function (b, recursive) {
if (!exports.info) {
exports.info = {
buf_stack: [],
block_stack: [],
blocks: {},
level: 1
}
}
exports.info.buf = b;
}
exports.begin_capture = function() {
exports.info.buf_stack.push(exports.info.buf.concat());
exports.info.buf.splice(0, exports.info.buf.length);
}
exports.end_capture = function () {
var res = exports.info.buf.join("");
exports.info.buf.splice.apply(
exports.info.buf,
[0, exports.info.buf.length].concat(exports.info.buf_stack.pop()));
return res;
}
exports.begin_define_block = function (name) {
if (typeof exports.info.blocks[name] == "undefined")
exports.info.blocks[name] = {};
exports.info.block_stack.push(name);
exports.begin_capture();
}
exports.end_define_block = function () {
content = exports.end_capture();
var name = exports.info.block_stack.pop();
if (typeof exports.info.blocks[name].content == "undefined")
exports.info.blocks[name].content = content;
return exports.info.blocks[name].content;
}
exports.end_block = function () {
var res = exports.end_define_block();
exports.info.buf.push(res);
}
exports.begin_block = exports.begin_define_block;
exports.require = function (name, args) {
if (args == undefined) args = {};
if (exports.info)
exports.info.buf_stack.push(exports.info.buf);
var res = ejs.render(
fs.readFileSync(require.resolve(name)).toString(),
args);
if (exports.info)
exports.info.buf = exports.info.buf_stack.pop();
if (exports.info.buf)
exports.info.buf.push(res);
return res;
}
<% var e = require("./eejs.js"); e.init(buf); %>
<% e.begin_define_block("foo"); %>
YY
<% e.end_define_block(); %>
<% e.require("./bar.ejs"); %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment