Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rendering jade template with layout (without express)

When you render jade templates in express you can configure your application with 'view options', { layout: true } and the templates rendered will automatically get plugged into the body local of the layout template.

I'm trying to achieve the equivalent behavior rendering files from node.js, but without the express framework (I'm just building static files as part of a larger pipeline).

There appear to be two options:

  • Load both the main template and the layout, convert to functions, render the template first and then pass the results to the layout function
  • Use the standard template inheritance and block structure, but then I'm explicitly using named blocks

Are these the only options (which, fair enough, are still awesome), or am I missing some trick?


Edit

Here's a rough cut of the first option in case anyone is interested:

// Load jade
var jade = require('jade');

// Load actual template text
var layout = fs.readFileSync('layout-path', 'utf8')
    tpl = fs.readFileSync('tpl-path', 'utf8');

// Compile template rendering function
layout = jade.compile(layout, { pretty: true, filename: 'layout-path' });
tpl = jade.compile(tpl, { pretty: true, filename: 'tpl-path' });

// Render jade template, passing in the info
var output = layout({ body: tpl({ local1: some_var, local2: some_var }) }

// Write rendered content to file
fs.writeFileSync('output.html', output);
like image 346
AJ. Avatar asked Feb 22 '12 16:02

AJ.


1 Answers

I believe the answer is "no", you're not missing any trick. The two options you outline seem to me the two most straightforward ways to use jade to generate your file. Of course there are plenty of non-jade approaches as well. For example, you could merge the contents with the plates approach, good old String.replace, or split your layout into separate header ad footer fragment files and just concatenate them in head, body, foot order.

like image 151
Peter Lyons Avatar answered Oct 15 '22 15:10

Peter Lyons