diff --git a/src/shared/getMetaInfo.js b/src/shared/getMetaInfo.js index 284b703..92613b0 100644 --- a/src/shared/getMetaInfo.js +++ b/src/shared/getMetaInfo.js @@ -84,7 +84,11 @@ export default function _getMetaInfo (options = {}) { // replace title with populated template if (info.titleTemplate) { - info.title = info.titleTemplate.replace(/%s/g, info.titleChunk) + if (typeof info.titleTemplate === 'function') { + info.title = info.titleTemplate.call(component, info.titleChunk) + } else { + info.title = info.titleTemplate.replace(/%s/g, info.titleChunk) + } } // convert base tag to an array so it can be handled the same way diff --git a/test/getMetaInfo.spec.js b/test/getMetaInfo.spec.js index 35572a8..c69a644 100644 --- a/test/getMetaInfo.spec.js +++ b/test/getMetaInfo.spec.js @@ -69,4 +69,102 @@ describe('getMetaInfo', () => { __dangerouslyDisableSanitizers: [] }) }) + + it('properly uses string titleTemplates', () => { + component = new Vue({ + metaInfo: { + title: 'Hello', + titleTemplate: '%s World', + meta: [ + { charset: 'utf-8' } + ] + } + }) + expect(getMetaInfo(component)).to.eql({ + title: 'Hello World', + titleChunk: 'Hello', + titleTemplate: '%s World', + htmlAttrs: {}, + headAttrs: {}, + bodyAttrs: {}, + meta: [ + { charset: 'utf-8' } + ], + base: [], + link: [], + style: [], + script: [], + noscript: [], + __dangerouslyDisableSanitizers: [] + }) + }) + + it('properly uses function titleTemplates', () => { + const titleTemplate = chunk => `${chunk} Function World` + + component = new Vue({ + metaInfo: { + title: 'Hello', + titleTemplate: titleTemplate, + meta: [ + { charset: 'utf-8' } + ] + } + }) + expect(getMetaInfo(component)).to.eql({ + title: 'Hello Function World', + titleChunk: 'Hello', + titleTemplate: titleTemplate, + htmlAttrs: {}, + headAttrs: {}, + bodyAttrs: {}, + meta: [ + { charset: 'utf-8' } + ], + base: [], + link: [], + style: [], + script: [], + noscript: [], + __dangerouslyDisableSanitizers: [] + }) + }) + + it('has the proper `this` binding when using function titleTemplates', () => { + const titleTemplate = function (chunk) { + return `${chunk} ${this.helloWorldText}` + } + + component = new Vue({ + metaInfo: { + title: 'Hello', + titleTemplate: titleTemplate, + meta: [ + { charset: 'utf-8' } + ] + }, + data () { + return { + helloWorldText: 'Function World' + } + } + }) + expect(getMetaInfo(component)).to.eql({ + title: 'Hello Function World', + titleChunk: 'Hello', + titleTemplate: titleTemplate, + htmlAttrs: {}, + headAttrs: {}, + bodyAttrs: {}, + meta: [ + { charset: 'utf-8' } + ], + base: [], + link: [], + style: [], + script: [], + noscript: [], + __dangerouslyDisableSanitizers: [] + }) + }) })