Skip to content

Commit

Permalink
feat: add 'each .. of ..' syntax to support all iterable objects (inc…
Browse files Browse the repository at this point in the history
…luding Arrays) (pugjs#3179)
  • Loading branch information
maxrumsey authored and ForbesLindesay committed Sep 16, 2019
1 parent f0fb46a commit ca4e7ce
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
34 changes: 34 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -971,6 +971,39 @@ Lexer.prototype = {
}
},

/**
* EachOf.
*/

eachOf: function() {
var captures;
if (captures = /^(?:each|for) (.*) of *([^\n]+)/.exec(this.input)) {
this.consume(captures[0].length);
var tok = this.tok('eachOf', captures[1]);
tok.value = captures[1];
this.incrementColumn(captures[0].length - captures[2].length);
this.assertExpression(captures[2])
tok.code = captures[2];
this.incrementColumn(captures[2].length);
this.tokens.push(this.tokEnd(tok));

if (!(/^[a-zA-Z_$][\w$]*$/.test(tok.value.trim()) || /^\[ *[a-zA-Z_$][\w$]* *\, *[a-zA-Z_$][\w$]* *\]$/.test(tok.value.trim()))) {
this.error(
'MALFORMED_EACH_OF_LVAL',
'The value variable for each must either be a valid identifier (e.g. `item`) or a pair of identifiers in square brackets (e.g. `[key, value]`).'
);
}

return true;
}
if (captures = /^- *(?:each|for) +([a-zA-Z_$][\w$]*)(?: *, *([a-zA-Z_$][\w$]*))? +of +([^\n]+)/.exec(this.input)) {
this.error(
'MALFORMED_EACH',
'Pug each and for should not be prefixed with a dash ("-"). They are pug keywords and not part of JavaScript.'
);
}
},

/**
* Code.
*/
Expand Down Expand Up @@ -1485,6 +1518,7 @@ Lexer.prototype = {
|| this.callLexerFunction('mixin')
|| this.callLexerFunction('call')
|| this.callLexerFunction('conditional')
|| this.callLexerFunction('eachOf')
|| this.callLexerFunction('each')
|| this.callLexerFunction('while')
|| this.callLexerFunction('tag')
Expand Down
1 change: 1 addition & 0 deletions test/check-lexer-functions.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ var lexerFunctions = {
doctype: true,
dot: true,
each: true,
eachOf: true,
eos: true,
endInterpolation: true,
extends: true,
Expand Down

0 comments on commit ca4e7ce

Please sign in to comment.