UNPKG

2.2 kBJavaScriptView Raw
1var _ = require('lodash'),
2 dateformat = require('dateformat');
3
4/**
5 * Pre-defined functions which can be used as template functions.
6 * When these functions are applied to the current page, it uses page + templates + params as its context.
7 *
8 * @param {String} page: current page which these functions will be applied to
9 * @param {Object} templates: compiled jazz templates
10 * @param {Object} params: template parameters (including user-defined parameters and custom functions)
11 */
12module.exports = function (page, templates, params) {
13
14 /**
15 * Display the current date in specified format.
16 * Default to ISO date when format is not specified.
17 *
18 * @param {String} format: date format (felixge/node-dateformat)
19 * @param {Function} cb: jazz cb(data) callback
20 */
21 function date(format, cb) {
22 cb(dateformat(new Date(), format || 'isoDateTime'));
23 }
24
25 /**
26 * Include a partial template in the current page.
27 * An error message will be included when partial does not exist.
28 *
29 * @param {String} partial: partial template file to include
30 * @param {Function} cb: jazz cb(data) callback
31 */
32 function include(partial, cb) {
33 cb((params.partials && params.partials[partial]) ?
34 params.partials[partial] :
35 '[error] partial ' + partial + ' does not exist');
36 }
37
38 /**
39 * Prefix path with one ../ for each parent directory of the page.
40 * This is used to construct static links from various directory level in the website.
41 *
42 * @param {String} path: a URL path in the site navigation
43 * @param {Function} cb: jazz cb(data) callback
44 */
45 function relative(path, cb) {
46 var value = path;
47 for (var i = 0, ln = page.length; i < ln; i += 1) {
48 if (page.charAt(i) === '/') {
49 value = '../' + value;
50 }
51 }
52 cb(value);
53 }
54
55 /**
56 * Display current page's sitemap title.
57 *
58 * @param {Function} cb: jazz cb(data) callback
59 */
60 function title(cb) {
61 cb((params.sitemap && params.sitemap[page]) ?
62 params.sitemap[page].title :
63 '[error] page ' + page + ' does not have any sitemap title');
64 }
65
66 return {
67 date: date,
68 include: include,
69 relative: relative,
70 title: title
71 };
72};