UNPKG

2.06 kBJavaScriptView Raw
1'use strict';
2
3/**
4 * Jade plugin for Crixalis.
5 * Provides simple wrapper around [Jade](http://jade-lang.com) template engine.
6 * @module Crixalis
7 * @submodule jade
8 * @for Controller
9 */
10
11var define = require('../controller').define,
12 jade = require('jade'),
13 fs = require('fs'),
14 cache = {};
15
16module.exports = function (options) {
17 options = options || {};
18
19 /**
20 * Templates parent directory
21 * @property jadePath
22 * @type String
23 * @default .
24 */
25 define('property', 'jadePath', '.');
26
27 /**
28 * Render Jade template. Template parameters are taken from this.stash.
29 *
30 * c.jadePath = './templates';
31 *
32 * c.router('/')
33 * .to(function () {
34 * this.jade('index.jade');
35 * });
36 *
37 * @method jade
38 * @param {String} template Path to Jade template
39 * @chainable
40 */
41 define('method', 'jade', function (template) {
42 var that = this;
43
44 if (typeof template !== 'string') {
45 throw new Error('Template expected to be string');
46 }
47
48 if (this.jadePath) {
49 template = this.jadePath + '/' + template;
50 }
51
52 fs.lstat(template, function (error, result) {
53 var cached = cache[template],
54 mtime;
55
56 if (error) {
57 /* File not found */
58 that.error(error, true);
59 return;
60 }
61
62 mtime = +result.mtime;
63
64 /* Best case, template is already compiled */
65 if (cached && cached.mtime === mtime) {
66 that.body = cached(that.stash);
67 that.render('html');
68 return;
69 }
70
71 /* No cached template, read from disk */
72 fs.readFile(template, function (error, result) {
73 if (error) {
74 /* File not found or is not readable */
75 that.error(error, true);
76 return;
77 }
78
79 /* Jade needs filename for includes and error reporting */
80 options.filename = template;
81
82 try {
83 cached = jade.compile(result, options);
84 that.body = cached(that.stash);
85 } catch (error) {
86 /* Compilation failed */
87 that.error(error, true);
88 return;
89 }
90
91 cached.mtime = mtime;
92 cache[template] = cached;
93
94 that.render('html');
95 });
96 });
97
98 return this;
99 });
100};