-
-
Notifications
You must be signed in to change notification settings - Fork 71
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: implement
fallbackTitle
as separate plugin
- Loading branch information
Showing
2 changed files
with
47 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
import { defineNuxtPlugin } from 'nuxt/app' | ||
import type { UseHeadOptions } from '@unhead/vue' | ||
import { withoutTrailingSlash } from 'ufo' | ||
import { | ||
computed, | ||
useHead, | ||
useRoute, | ||
} from '#imports' | ||
|
||
function titleCase(s: string) { | ||
return s | ||
.replaceAll('-', ' ') | ||
.replace(/\w\S*/g, w => w.charAt(0).toUpperCase() + w.substr(1).toLowerCase()) | ||
} | ||
|
||
export default defineNuxtPlugin({ | ||
name: 'nuxt-seo:fallback-titles', | ||
setup() { | ||
const route = useRoute() | ||
const title = computed(() => { | ||
if (typeof route.meta?.title === 'string') | ||
return route.meta?.title | ||
// if no title has been set then we should use the last segment of the URL path and title case it | ||
const path = withoutTrailingSlash(route.path || '/') | ||
const lastSegment = path.split('/').pop() | ||
return lastSegment ? titleCase(lastSegment) : null | ||
}) | ||
|
||
const minimalPriority: UseHeadOptions = { | ||
// give nuxt.config values higher priority | ||
tagPriority: 101, | ||
} | ||
|
||
useHead({ title }, minimalPriority) | ||
}, | ||
}) |