Skip to content

Commit

Permalink
Fix parsing error about <code> tag (Issue #2563) (#2568)
Browse files Browse the repository at this point in the history
  • Loading branch information
seaoak authored and NoahDragon committed May 17, 2017
1 parent 4f6c384 commit 7f933d4
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 2 deletions.
10 changes: 8 additions & 2 deletions lib/extend/tag.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
'use strict';

var assert = require('assert');
var stripIndent = require('strip-indent');
var nunjucks = require('nunjucks');
var inherits = require('util').inherits;
Expand Down Expand Up @@ -46,6 +47,8 @@ Tag.prototype.register = function(name, fn, options) {

var placeholder = '\uFFFC';
var rPlaceholder = /(?:<|&lt;)\!--\uFFFC(\d+)--(?:>|&gt;)/g;
var rTagCode = /<code[\s>]/i;
var rTagPre = /<pre[\s>]/i;

Tag.prototype.render = function(str, options, callback) {
if (!callback && typeof options === 'function') {
Expand All @@ -55,14 +58,17 @@ Tag.prototype.render = function(str, options, callback) {

var cache = [];

function escapeContent(str) {
function escapeContent(str, p1, p2, p3) {
assert(!p1 === !p3, '<pre> tag should be coupled: "' + p1 + '" <=> "' + p3 + '"');
assert(!rTagCode.test(p2), '<code> tag should not be nested');
assert(!rTagPre.test(p2), '<pre> tag should not be nested');
return '<!--' + placeholder + (cache.push(str) - 1) + '-->';
}

var env = this.env;

return new Promise(function(resolve, reject) {
str = str.replace(/(?:<pre>)?<code.*>[\s\S]*?<\/code>(?:<\/pre>)?/gm, escapeContent);
str = str.replace(/(<pre>)?<code.*?>([\s\S]*?)<\/code>(<\/pre>)?/gm, escapeContent);
env.renderString(str, options, function(err, result) {
if (err) return reject(err);
resolve(result.replace(rPlaceholder, function() {
Expand Down
45 changes: 45 additions & 0 deletions test/scripts/extend/tag.js
Original file line number Diff line number Diff line change
Expand Up @@ -164,4 +164,49 @@ describe('Tag', () => {
result.should.eql(str);
});
});

it('render() - ignore mixed repeated <code>', function() {
var str = `
aaa
{% test1 foo.jpg %}
<pre><code>{{ helper.json1() }}</code></pre>
bbb
{% test2 foo2.jpg %}
ccc
<code>{{ helper.json2() }}</code>
{% test3 foo3.jpg %}
ddd
<code>{{ helper.json3() }}</code>
{% test4 foo4.jpg %}
<pre><code>{{ helper.json4() }}</code></pre>
eee
{% test5 foo5.jpg %}
fff
`;
var expected = str.replace(/\{\% (test\d) (\S+) \%\}/g, '$1=$2');

tag.register('test1', (args, content) => 'test1=' + args.join('='));
tag.register('test2', (args, content) => 'test2=' + args.join('='));
tag.register('test3', (args, content) => 'test3=' + args.join('='));
tag.register('test4', (args, content) => 'test4=' + args.join('='));
tag.register('test5', (args, content) => 'test5=' + args.join('='));

return tag.render(str).then(function(result) {
result.should.eql(expected);
});
});
});

0 comments on commit 7f933d4

Please sign in to comment.