Skip to content

Commit

Permalink
fix: parse template params in titleTemplate functions
Browse files Browse the repository at this point in the history
Fixes #282
  • Loading branch information
harlan-zw committed Sep 7, 2024
1 parent 7886d6f commit d5741c5
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
17 changes: 16 additions & 1 deletion packages/unhead/src/plugins/templateParams.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { defineHeadPlugin, processTemplateParams } from '@unhead/shared'
import type { TemplateParams } from '@unhead/schema'
import type {HeadTag, TemplateParams} from '@unhead/schema'

const SupportedAttrs = {
meta: 'content',
Expand Down Expand Up @@ -60,5 +60,20 @@ export default defineHeadPlugin(head => ({
head._templateParams = params
head._separator = sep
},
'tags:afterResolve': ({ tags }) => {
// we need to re-process in case then user had a function as the titleTemplate
// TODO drop support for function in v2
let title: HeadTag | undefined
for (let i = 0; i < tags.length; i += 1) {
const tag = tags[i]

if (tag.tag === 'title' && tag.processTemplateParams !== false) {
title = tag
}
}
if (title?.textContent) {
title.textContent = processTemplateParams(title.textContent, head._templateParams!, head._separator!)
}
},
},
}))
18 changes: 18 additions & 0 deletions test/unhead/ssr/titleTemplate.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,4 +84,22 @@ describe('titleTemplate', () => {
`""`,
)
})
it('function titleTemplate with templateParams', async () => {
const head = createHead()
head.push({
titleTemplate: () => '%s %separator %subPage% %separator %site.name',
title: 'test %foo',
templateParams: {
site: {
name: 'test',
},
subPage: 'subPage',
foo: 'foo',
},
})
const { headTags } = await renderSSRHead(head)
expect(headTags).toMatchInlineSnapshot(
`"<title>test foo | subPage% | test</title>"`,
)
})
})

0 comments on commit d5741c5

Please sign in to comment.