-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainNavLangs.astro
More file actions
92 lines (81 loc) · 2.42 KB
/
Copy pathMainNavLangs.astro
File metadata and controls
92 lines (81 loc) · 2.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
---
// IMPORTS
import type { Multi } from "@types";
import { languages } from "@i18n/ui";
import { getRoutes, sanitizeRoutes } from "@i18n/utils";
import { getEntry } from "astro:content";
// ACTIONS
// Get locale
const { locale } = Astro.props;
// Determine current slug from pathname
let currentPath = Astro.url.pathname;
// Base paths for top-level pages with different paths across locales
let base: string = "";
let lang_bases: string | Multi;
if (
currentPath.startsWith("/services/") ||
currentPath.startsWith("/servicios/") ||
currentPath.startsWith("/palvelut/")
) {
base = currentPath.split("/")[1];
lang_bases = getRoutes(base);
}
// Alt slugs for collection items with different paths across languages
const parts = currentPath.split("/");
let slug: string | undefined = parts.pop() || parts.pop();
const routes: Multi | string = getRoutes(slug);
// Get rid of flags for locales where page does not exist
let valid_langs = Object.keys(languages);
let lang_slugs =
typeof routes === "string" ? [slug, slug, slug] : Object.values(routes);
if (parts.includes("blog") && parts.slice(-1)[0] != "blog") {
valid_langs = [];
let items: (object | undefined)[] = [];
for (let i = 0; i < Object.keys(languages).length; i++) {
const post_in_lang = await getEntry(
"blog",
`${Object.keys(languages)[i]}/${lang_slugs[i]}`,
);
items.push(post_in_lang);
}
const do_posts_exist = items.every((item) => !item)
? [true, true, true]
: items.map((post) => {
return post !== undefined;
}); // Note to self. Do not remove conditional. Avoids error with paginated views.
for (let i = 0; i < Object.keys(languages).length; i++) {
if (do_posts_exist[i]) {
valid_langs.push(Object.keys(languages)[i]);
}
}
}
---
<span class="flex items-center justify-center">
{
valid_langs.map((l) => (
<a
href={sanitizeRoutes(
typeof routes === "object"
? currentPath
.replace(`/${locale}/`, `/${l}/`)
.replace(`/${slug}/`, `/${routes[l]}/`)
.replace(`/${slug}`, `/${routes[l]}/`)
: currentPath
.replace(
base,
typeof lang_bases === "object" ? lang_bases[l] : base,
)
.replace(`/${locale}/`, `/${l}/`)
.replace(`/${locale}`, `/${l}/`),
)}
aria-label={`Change language to ${l}`}
>
<img
src={`/icons/${l}.svg`}
alt={`Icon flag for ${l} language.`}
class="ml-1 w-8 h-8 hover:animate-pulse"
/>
</a>
))
}
</span>