diff --git a/lib/extend/injector.js b/lib/extend/injector.js index 116e39cbff..ed25e1041c 100644 --- a/lib/extend/injector.js +++ b/lib/extend/injector.js @@ -1,5 +1,7 @@ 'use strict'; +const { Cache } = require('hexo-util'); + class Injector { constructor() { this.store = { @@ -8,6 +10,8 @@ class Injector { body_begin: {}, body_end: {} }; + + this.cache = new Cache(); } list() { @@ -33,6 +37,45 @@ class Injector { valueSet.add(value); entryMap[to] = valueSet; } + + exec(data, locals = { page: {} }) { + let currentType = 'default'; + const { page } = locals; + + if (page.__index) currentType = 'home'; + if (page.__post) currentType = 'post'; + if (page.__page) currentType = 'page'; + if (page.archive) currentType = 'archive'; + if (page.category) currentType = 'category'; + if (page.tag) currentType = 'tag'; + if (page.layout) currentType = page.layout; + + const injector = (data, pattern, flag, isBegin = true) => { + if (data.includes(`hexo injector ${flag}`)) return data; + + const code = this.cache.apply(`${flag}-${currentType}-code`, () => { + const content = currentType === 'default' ? this.getText(flag, 'default') : this.getText(flag, currentType) + this.getText(flag, 'default'); + + if (!content.length) return ''; + return '' + content + ''; + }); + + // avoid unnesscary replace() for better performance + if (!code.length) return data; + return data.replace(pattern, str => { return isBegin ? str + code : code + str; }); + }; + + // Inject head_begin + data = injector(data, /