UNPKG

twing

Version:

First-class Twig engine for Node.js

55 lines (54 loc) 2.53 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.createMacroTagHandler = void 0; /** * Defines a macro. * * <pre> * {% macro input(name, value, type, size) %} * <input type="{{ type|default('text') }}" name="{{ name }}" value="{{ value|e }}" size="{{ size|default(20) }}" /> * {% endmacro %} * </pre> */ const parsing_1 = require("../error/parsing"); const macro_1 = require("../node/macro"); const get_key_value_pairs_1 = require("../helpers/get-key-value-pairs"); const node_1 = require("../../lib/node"); const createMacroTagHandler = () => { const tag = 'macro'; return { tag, initialize: (parser) => { return (token, stream) => { const { line, column } = token; const name = stream.expect("NAME").value; const macroArguments = parser.parseArguments(stream, true, true); for (const { key, value: macroArgument } of (0, get_key_value_pairs_1.getKeyValuePairs)(macroArguments)) { const { value: argumentName } = key.attributes; if (argumentName === macro_1.VARARGS_NAME) { throw (0, parsing_1.createParsingError)(`The argument "${macro_1.VARARGS_NAME}" in macro "${name}" cannot be defined because the variable "${macro_1.VARARGS_NAME}" is reserved for arbitrary arguments.`, macroArgument, stream.source); } } stream.expect("TAG_END"); parser.pushLocalScope(); const body = parser.subparse(stream, tag, (token) => { return token.test("NAME", 'endmacro'); }); stream.next(); const nextToken = stream.nextIf("NAME"); if (nextToken) { const value = nextToken.value; if (value != name) { const { line, column } = nextToken; throw (0, parsing_1.createParsingError)(`Expected endmacro for macro "${name}" (but "${value}" given).`, { line, column }, stream.source); } } parser.popLocalScope(); stream.expect("TAG_END"); parser.setMacro(name, (0, macro_1.createMacroNode)(name, (0, node_1.createNode)({ body }, line, column), macroArguments, line, column, tag)); return null; }; } }; }; exports.createMacroTagHandler = createMacroTagHandler;