summaryrefslogtreecommitdiffstats
path: root/lib/templating/replaceShortcuts.js
blob: 66ddff3b51f834f28ee1958cb951fea36e6e4ec0 (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
38
39
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 start = shortcut.getStart();
    var end = shortcut.getEnd();

    var tagStart = shortcut.getStartTag();
    var tagEnd = shortcut.getEndTag();

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

/**
    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;