From 49d14859e96647a8dfa5f11f3eebe6c6c036c396 Mon Sep 17 00:00:00 2001 From: dalance Date: Tue, 25 Jun 2024 10:08:03 +0900 Subject: [PATCH] Add hreflang --- book/theme/head.hbs | 38 +++++++++++++++++++++++++++++--------- 1 file changed, 29 insertions(+), 9 deletions(-) diff --git a/book/theme/head.hbs b/book/theme/head.hbs index 92cbc9d7..03750751 100644 --- a/book/theme/head.hbs +++ b/book/theme/head.hbs @@ -13,23 +13,43 @@ // See these pages for details: // https://developers.google.com/search/docs/crawling-indexing/consolidate-duplicate-urls // https://developers.google.com/search/docs/crawling-indexing/javascript/javascript-seo-basics - let base = "https://doc.veryl-lang.org/book"; + + function gen_canonical_href(lang) { + let base = "https://doc.veryl-lang.org/book"; + let canonical_href; + if (lang == "en") { + canonical_href = `${base}/{{ path }}`; + } else { + canonical_href = `${base}/${lang}/{{ path }}`; + } + canonical_href = canonical_href.slice(0, -"md".length) + "html"; + if (canonical_href.endsWith("/index.html")) { + canonical_href = canonical_href.slice(0, -"index.html".length); + } + return canonical_href; + } + {{#if (eq language "en")}} - let canonical_href = `${base}/{{ path }}`; + const canonical_href = gen_canonical_href("en"); {{else}} - let canonical_href = `${base}/{{ language }}/{{ path }}`; + const canonical_href = gen_canonical_href("{{ language }}"); {{/if}} - // mdbook gives us a string ending in ".md", we replace it with ".html": - canonical_href = canonical_href.slice(0, -"md".length) + "html"; - if (canonical_href.endsWith("/index.html")) { - canonical_href = canonical_href.slice(0, -"index.html".length); - } - let link = document.createElement("link"); link.rel = "canonical"; link.href = canonical_href; document.head.appendChild(link); + + const langs = ["en", "ja"]; + for (const lang of langs) { + const canonical_href = gen_canonical_href(lang); + + let link = document.createElement("link"); + link.rel = "alternate"; + link.hreflang = lang; + link.href = canonical_href; + document.head.appendChild(link); + } })()