Skip to content

Commit

Permalink
feat: alternate links
Browse files Browse the repository at this point in the history
  • Loading branch information
johannschopplich committed Feb 13, 2024
1 parent c95860e commit b2ca054
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 8 deletions.
28 changes: 23 additions & 5 deletions composables/page.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { joinURL } from 'ufo'
import { kirbyStatic } from '#nuxt-kql'
import type { KirbyPageData } from '~/queries'

/**
* Returns static data prefetched at build time
Expand Down Expand Up @@ -30,6 +31,8 @@ export function setPage<T extends Record<string, any>>(page?: T) {

// Build the page meta tags
const { siteUrl } = useRuntimeConfig().public
const { $i18n: i18n } = useNuxtApp()
const { defaultLocale, locale } = i18n
const site = useSite()
const title = page.title
? `${page.title}${site.value.title}`
Expand All @@ -38,17 +41,32 @@ export function setPage<T extends Record<string, any>>(page?: T) {
const url = joinURL(siteUrl, useRoute().path)
const image = page?.cover?.url || site.value.cover?.url

// Build alternate URL
const i18nMeta = page.i18nMeta as KirbyPageData['i18nMeta']
const alternateUrls = Object.entries(i18nMeta).map(([lang, meta]) => {
// Remove homepage slug and add leading language prefix
const uri = getLocalizedPath(meta.uri.replace(/^home/, '/'), lang)

return {
rel: 'alternate',
hreflang: lang,
href: joinURL(siteUrl, uri),
}
})

// Add English link as `x-default` language
alternateUrls.push({
...alternateUrls.find((i) => i.hreflang === defaultLocale)!,
hreflang: 'x-default',
})

useHead({
bodyAttrs: {
'data-template': page.intendedTemplate || 'default',
},
link: [
{ rel: 'canonical', href: url },
{
rel: 'alternate',
hreflang: 'x-default',
href: url,
},
...alternateUrls.filter(({ hreflang }) => hreflang !== locale.value),
],
})

Expand Down
4 changes: 1 addition & 3 deletions middleware/redirects.global.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import type { Composer } from '#i18n'

export default defineNuxtRouteMiddleware((to) => {
const i18n = useNuxtApp().$i18n as Composer
const { $i18n: i18n } = useNuxtApp()
const { defaultLocale } = i18n

if (to.path === '/') {
Expand Down
11 changes: 11 additions & 0 deletions utils/locale.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,14 @@
import { joinURL, withLeadingSlash } from 'ufo'

export function getLocalizedPath(
slug: string,
locale: string,
{ ignorePrefix = false }: { ignorePrefix?: boolean } = {},
) {
const prefix = ignorePrefix ? '' : locale
return withLeadingSlash(joinURL(prefix, slug))
}

export function getNonLocalizedSlug(
param: string | string[],
locales: string[] = [],
Expand Down

0 comments on commit b2ca054

Please sign in to comment.