summaryrefslogtreecommitdiffstats
path: root/lib/templating/postRender.js
blob: ec67696f7e30eaacd9572abf7da7d33db94e3f25 (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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
var Promise = require('../utils/promise');


/**
    Replace position markers of blocks by body after processing
    This is done to avoid that markdown/asciidoc processer parse the block content

    @param {String} content
    @return {Object} {blocks: Set, content: String}
*/
function replaceBlocks(content, blocks) {
    var newContent = content.replace(/\{\{\-\%([\s\S]+?)\%\-\}\}/g, function(match, key) {
        var replacedWith = match;

        var block = blocks.get(key);
        if (block) {
            replacedWith = replaceBlocks(block.get('body'), blocks);
        }

        return replacedWith;
    });

    return newContent;
}

/**
    Post render a template:
        - Execute "post" for blocks
        - Replace block content

    @param {TemplateEngine} engine
    @param {TemplateOutput} content
    @return {Promise<String>}
*/
function postRender(engine, output) {
    var content = output.getContent();
    var blocks = output.getBlocks();

    var result = replaceBlocks(content, blocks);

    return Promise.forEach(blocks, function(block) {
        var post = block.get('post');

        if (!post) {
            return;
        }

        return post();
    })
    .thenResolve(result);
}

module.exports = postRender;