Skip to content

Commit

Permalink
Fix indentation of inline partials (#716)
Browse files Browse the repository at this point in the history
These changes fixes an indentation bug introduced when partials was
made to also be indented like its parent template. When partials are
rendered inline, it should not be indented with the amount of indentation
that the line already has.

Fixes #715
Refs #705
  • Loading branch information
yotammadem authored and phillipj committed Sep 13, 2019
1 parent 13cde04 commit d820d25
Show file tree
Hide file tree
Showing 4 changed files with 9,025 additions and 13 deletions.
17 changes: 10 additions & 7 deletions mustache.js
Expand Up @@ -122,7 +122,7 @@
function parseTemplate (template, tags) {
if (!template)
return [];

var lineHasNonSpace = false;
var sections = []; // Stack to hold section tokens
var tokens = []; // Buffer to hold the tokens
var spaces = []; // Indices of whitespace tokens on the current line
Expand Down Expand Up @@ -175,10 +175,11 @@

if (isWhitespace(chr)) {
spaces.push(tokens.length);
if (!nonSpace)
indentation += chr;
indentation += chr;
} else {
nonSpace = true;
lineHasNonSpace = true;
indentation += ' ';
}

tokens.push([ 'text', chr, start, start + 1 ]);
Expand All @@ -189,6 +190,7 @@
stripSpace();
indentation = '';
tagIndex = 0;
lineHasNonSpace = false;
}
}
}
Expand Down Expand Up @@ -222,7 +224,7 @@
throw new Error('Unclosed tag at ' + scanner.pos);

if (type == '>') {
token = [ type, value, start, scanner.pos, indentation, tagIndex ];
token = [ type, value, start, scanner.pos, indentation, tagIndex, lineHasNonSpace ];
} else {
token = [ type, value, start, scanner.pos ];
}
Expand Down Expand Up @@ -610,11 +612,11 @@
return this.renderTokens(token[4], context, partials, originalTemplate);
};

Writer.prototype.indentPartial = function indentPartial (partial, indentation) {
Writer.prototype.indentPartial = function indentPartial (partial, indentation, lineHasNonSpace) {
var filteredIndentation = indentation.replace(/[^ \t]/g, '');
var partialByNl = partial.split('\n');
for (var i = 0; i < partialByNl.length; i++) {
if (partialByNl[i].length) {
if (partialByNl[i].length && (i > 0 || !lineHasNonSpace)) {
partialByNl[i] = filteredIndentation + partialByNl[i];
}
}
Expand All @@ -626,11 +628,12 @@

var value = isFunction(partials) ? partials(token[1]) : partials[token[1]];
if (value != null) {
var lineHasNonSpace = token[6];
var tagIndex = token[5];
var indentation = token[4];
var indentedValue = value;
if (tagIndex == 0 && indentation) {
indentedValue = this.indentPartial(value, indentation);
indentedValue = this.indentPartial(value, indentation, lineHasNonSpace);
}
return this.renderTokens(this.parse(indentedValue, tags), context, partials, indentedValue);
}
Expand Down

0 comments on commit d820d25

Please sign in to comment.