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?


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);

Problem courtesy of: AJ.


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.

Solution courtesy of: Peter Lyons

稿源:Node.js Recipes (源链) | 关于 | 阅读提示

本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 前端开发 » Rendering jade template with layout (without express)

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录