all files / liquidjs/tags/ layout.js

100% Statements 34/34
100% Branches 4/4
100% Functions 5/5
100% Lines 34/34
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 54 55 56 57 58 59 60 61 62 63 64 65 66 67     111×   11× 11×   11× 11×     10× 10×     10×   10×   10×   10×         111×   25× 25×   25× 25× 24× 17×     25×     23× 23×   23× 12×   12× 12×         11× 11×            
const Liquid = require('..');
const Promise = require('any-promise');
const lexical = Liquid.lexical;
const assert = require('../src/util/assert.js');
 
module.exports = function(liquid) {
 
    liquid.registerTag('layout', {
        parse: function(token, remainTokens){
            var match = lexical.value.exec(token.args);
            assert(match, `illegal token ${token.raw}`);
 
            this.layout = match[0];
            this.tpls = liquid.parser.parse(remainTokens);
        },
        render: function(scope, hash) {
            var layout = Liquid.evalValue(this.layout, scope);
            var register = scope.get('liquid');
 
            // render the remaining tokens immediately
            return liquid.renderer.renderTemplates(this.tpls, scope)
                // now register.blocks contains rendered blocks
                .then(() => liquid.getTemplate(layout, register.root))
                // push the hash
                .then(templates => (scope.push(hash), templates))
                // render the parent
                .then(templates => liquid.renderer.renderTemplates(templates, scope))
                // pop the hash
                .then(partial => (scope.pop(), partial));
        }
    });
 
    liquid.registerTag('block', {
        parse: function(token, remainTokens){
            var match = /\w+/.exec(token.args);
            this.block = match ? match[0] : 'anonymous';
 
            this.tpls = [];
            var stream = liquid.parser.parseStream(remainTokens)
                .on('tag:endblock', () => stream.stop())
                .on('template', tpl => this.tpls.push(tpl))
                .on('end', () => {
                    throw new Error(`tag ${token.raw} not closed`);
                });
            stream.start();
        },
        render: function(scope){
            var register = scope.get('liquid');
            var html = register.blocks[this.block];
            // if not defined yet
            if (html === undefined) {
                return liquid.renderer.renderTemplates(this.tpls, scope)
                    .then((partial) => {
                        register.blocks[this.block] = partial;
                        return partial;
                    });
            }
            // if already defined by desendents
            else {
                register.blocks[this.block] = html;
                return Promise.resolve(html);
            }
        }
    });
 
};