From c1c5aaaf95552f009f9d35a78f0e3b395866e7b8 Mon Sep 17 00:00:00 2001 From: Uiolee <22849383+uiolee@users.noreply.github.com> Date: Thu, 18 Jan 2024 13:09:16 +0800 Subject: [PATCH] fix(escapeAllSwigTags): check tag completeness (#5395) --- lib/hexo/post.ts | 4 ++++ test/scripts/hexo/post.js | 29 ++++++++++++++++++++++++++++- 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/lib/hexo/post.ts b/lib/hexo/post.ts index b7ecf3e988..0d6810a50e 100644 --- a/lib/hexo/post.ts +++ b/lib/hexo/post.ts @@ -69,6 +69,9 @@ class PostRenderEscape { * @returns string */ escapeAllSwigTags(str: string) { + if (!/(\{\{.+?\}\})|(\{#.+?#\})|(\{%.+?%\})/.test(str)) { + return str; + } let state = STATE_PLAINTEXT; let buffer = ''; let output = ''; @@ -86,6 +89,7 @@ class PostRenderEscape { if (state === STATE_PLAINTEXT) { // From plain text to swig if (char === '{') { + // check if it is a complete tag {{ }} if (next_char === '{') { state = STATE_SWIG_VAR; idx++; diff --git a/test/scripts/hexo/post.js b/test/scripts/hexo/post.js index 6dd792f617..cf7dd423b2 100644 --- a/test/scripts/hexo/post.js +++ b/test/scripts/hexo/post.js @@ -12,7 +12,7 @@ const escapeSwigTag = str => str.replace(/{/g, '{').replace(/}/g, '}') describe('Post', () => { const Hexo = require('../../../dist/hexo'); const hexo = new Hexo(join(__dirname, 'post_test')); - require('../../../lib/plugins/highlight/')(hexo); + require('../../../dist/plugins/highlight/')(hexo); const { post } = hexo; const now = Date.now(); let clock; @@ -1369,4 +1369,31 @@ describe('Post', () => { hexo.config.syntax_highlighter = 'highlight.js'; }); + + // https://github.com/hexojs/hexo/issues/5301 + it('render() - dont escape uncomplete tags', async () => { + const content = 'dont drop `{% }` 11111 `{# }` 22222 `{{ }` 33333'; + + const data = await post.render(null, { + content, + engine: 'markdown' + }); + + data.content.should.contains('11111'); + data.content.should.contains('22222'); + data.content.should.contains('33333'); + data.content.should.not.contains('`'); // ` + }); + + it('render() - uncomplete tags throw error', async () => { + const content = 'nunjucks should thorw {# } error'; + + try { + await post.render(null, { + content, + engine: 'markdown' + }); + should.fail(); + } catch (err) {} + }); });