summaryrefslogtreecommitdiffstats
path: root/lib/templating/replaceShortcuts.js
blob: f6a51cb474704b7e9d4875e1811ca1a613f67356 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
var escapeStringRegexp = require('escape-string-regexp');
var listShortcuts = require('./listShortcuts');

/*
    Apply a shortcut of block to a template
    @param {String} content
    @param {Shortcut} shortcut
    @return {String}
*/
function applyShortcut(content, shortcut) {
    var tags = shortcut.get('tag');
    var start = shortcut.get('start');
    var end = shortcut.get('end');

    var regex = new RegExp(
        escapeStringRegexp(start) + '([\\s\\S]*?[^\\$])' + escapeStringRegexp(end),
       'g'
    );
    return content.replace(regex, function(all, match) {
        return '{% ' + tags.start + ' %}' + match + '{% ' + tags.end + ' %}';
    });
}

/**
    Replace shortcuts from blocks in a string

    @param {TemplateEngine} engine
    @param {String} filePath
    @param {String} content
    @return {String}
*/
function replaceShortcuts(engine, filePath, content) {
    var shortcuts = listShortcuts(engine, filePath);
    return shortcuts.reduce(applyShortcut, content);
}

module.exports = replaceShortcuts;