Skip to content

Commit

Permalink
Refactor nunjucks utils and add additional nested test case
Browse files Browse the repository at this point in the history
  • Loading branch information
crphang committed Feb 24, 2020
1 parent 30cffe0 commit be7d653
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 8 deletions.
1 change: 1 addition & 0 deletions src/Page.js
Original file line number Diff line number Diff line change
Expand Up @@ -1043,6 +1043,7 @@ class Page {
isDynamic: true,
dynamicSource: source,
}))
.then(result => nunjuckUtils.removeNunjucksEscapes(result))
.then(result => fs.outputFileAsync(tempPath, result))
.then(() => markbinder.renderFile(tempPath, {
baseUrlMap: this.baseUrlMap,
Expand Down
14 changes: 6 additions & 8 deletions src/lib/markbind/nunjuckUtils.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,17 @@
const START_ESCAPE_STR = '{% raw %}';
const END_ESCAPE_STR = '{% endraw %}';
const regex = new RegExp('({%( *)raw( *)%})(.*?)({%( *)endraw( *)%})', 'gs');
const REGEX = new RegExp('{% *raw *%}(.*?){% *endraw *%}', 'gs'); // eslint-disable-line no-useless-escape

function addEscapeTags(match) {
return START_ESCAPE_STR + match + END_ESCAPE_STR;
return `${START_ESCAPE_STR}${match}${END_ESCAPE_STR}`;
}

function removeEscapeTags(match, p1, p2, p3, p4) {
return p4;
function removeEscapeTags(_, p1) {
return p1;
}

function preEscapeRawTags(pageData) {
const replaced = pageData.replace(regex, addEscapeTags);
return replaced;
return pageData.replace(REGEX, addEscapeTags);
}

module.exports = {
Expand All @@ -22,7 +21,6 @@ module.exports = {
},

removeNunjucksEscapes(pageData) {
const replaced = pageData.replace(regex, removeEscapeTags);
return replaced;
return pageData.replace(REGEX, removeEscapeTags);
},
};
6 changes: 6 additions & 0 deletions test/unit/nunjuckUtils.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,12 @@ test('Escaping multiple nunjucks raw tags', () => {
expect(escapedContent).toBe(escapedString);
});

test('Escaping nested nunjucks raw tags', () => {
const escapedString = 'Nested escaped data: {% raw %} {% raw %} CONTENT {% endraw %}{% endraw %}';
const escapedContent = nunjuckUtils.renderEscaped(nunjucks, escapedString);
expect(escapedContent).toBe(escapedString);
});

test('Removing Nunjucks Raw Tags', () => {
const escapedString = 'This is a content with escaped data {%raw%} CONTENT {%endraw%}';
const removedEscapedString = nunjuckUtils.removeNunjucksEscapes(escapedString);
Expand Down

0 comments on commit be7d653

Please sign in to comment.