bminer / node-blade

Blade - HTML Template Compiler, inspired by Jade & Haml
Other
320 stars 28 forks source link

Lowest possible server-side memory usage #186

Closed da99 closed 10 years ago

da99 commented 10 years ago

Is there are way to compile templates to a self-contained file and run them w/o the need for require('blade') on the server-side?

For example:

# command line
blade -C my_file.blade

# Server-side
var b = require("./my_file");
var html = b(local, cb);
da99 commented 10 years ago

I found one way. Hack-ish, but it works so far (as long as you don't refer to an external file (eg a layout)):

# command line:
wget https://raw.github.com/bminer/node-blade/master/lib/runtime.js
echo "var window = {};"            >   my_blade.js
cat runtime.js                    >>  my_blade.js
echo "var blade = window.blade;"  >> my_blade.js

blade -C    my.blade    my_compiled.js

cat  my_compiled.js               >> my_blade.js
echo "exports.tmpl = anonymous;"  >> my_blade.js

# in Node.js
var b = require('./my_blade');
b.tmpl({my_var: "str"}, function (err, html, meta) {
     console.log(html);
});
bminer commented 10 years ago

@da99 - You bring up an interesting point. Alternatively, you can just require the Blade runtime like this: require("blade/lib/runtime") instead of require("blade"). This will only load the runtime into memory.

Something like this shell script might work, as well (perhaps slightly less hack-ish):

# Inside of your Node project root dir
npm install blade
echo "module.exports = " > my.blade.js
blade -C my.blade >> my.blade.js
# Or perhaps change to: `blade -C --minify my.blade >> my.blade.js`

And in Node...

var bladeRuntime = require("blade/lib/runtime");
var myBladeTemplate = require("./my.blade");
var buf = [];
buf.r = bladeRuntime;
myBladeTemplate({my_var: "str"}, function (err, html, meta) {
     console.log(html);
}, buf);

The trick here is passing the runtime into the view via the buf Array. A bit sneaky...

da99 commented 10 years ago

Thanks, Blake. This is much better and easier than what I had.