Skip to content

Commit ecc0e04

Browse files
RomakitaQingWei-Li
authored andcommitted
feat(fetch): Add fallback languages configuration. (#402)
fallbackLanguages give the possibility to configure a list of languages which must used the default language when a page is missing in the requested language.
1 parent 278a75e commit ecc0e04

File tree

2 files changed

+56
-11
lines changed

2 files changed

+56
-11
lines changed

docs/configuration.md

+22
Original file line numberDiff line numberDiff line change
@@ -413,3 +413,25 @@ window.$docsify = {
413413
ext: '.md'
414414
};
415415
```
416+
417+
## fallbackLanguages
418+
419+
* type: `Array<string>`
420+
421+
List of languages that will fallback to the default language when a page is request and didn't exists for the given local.
422+
423+
Example:
424+
425+
- try to fetch the page of `/de/overview`. If this page exists, it'll be displayed
426+
- then try to fetch the default page `/overview` (depending on the default language). If this page exists, it'll be displayed
427+
- then display 404 page.
428+
429+
430+
```js
431+
window.$docsify = {
432+
fallbackLanguages: [
433+
"fr",
434+
"de"
435+
]
436+
};
437+
```

src/core/fetch/index.js

+34-11
Original file line numberDiff line numberDiff line change
@@ -22,18 +22,40 @@ export function fetchMixin (proto) {
2222
proto._fetch = function (cb = noop) {
2323
const { path, query } = this.route
2424
const qs = stringifyQuery(query, ['id'])
25-
const { loadNavbar, loadSidebar, requestHeaders } = this.config
26-
25+
const { loadNavbar, loadSidebar, requestHeaders, fallbackLanguages } = this.config
2726
// Abort last request
2827
last && last.abort && last.abort()
2928

3029
const file = this.router.getFile(path)
31-
3230
last = get(file + qs, true, requestHeaders)
3331

3432
// Current page is html
3533
this.isHTML = /\.html$/g.test(file)
3634

35+
const getFallBackPage = (file) => {
36+
if (!fallbackLanguages) {
37+
return false
38+
}
39+
40+
const local = file.split('/')[1]
41+
42+
if (fallbackLanguages.indexOf(local) === -1) {
43+
return false
44+
}
45+
46+
file = file.replace(new RegExp(`^/${local}`), '')
47+
48+
return get(file + qs, true, requestHeaders)
49+
.then(
50+
(text, opt) => {
51+
this._renderMain(text, opt, loadSideAndNav)
52+
},
53+
_ => {
54+
return this._renderMain(null, {}, loadSideAndNav)
55+
}
56+
)
57+
}
58+
3759
const loadSideAndNav = () => {
3860
if (!loadSidebar) return cb()
3961

@@ -47,14 +69,15 @@ export function fetchMixin (proto) {
4769
}
4870

4971
// Load main content
50-
last.then(
51-
(text, opt) => {
52-
this._renderMain(text, opt, loadSideAndNav)
53-
},
54-
_ => {
55-
this._renderMain(null, {}, loadSideAndNav)
56-
}
57-
)
72+
last
73+
.then(
74+
(text, opt) => {
75+
this._renderMain(text, opt, loadSideAndNav)
76+
},
77+
_ => {
78+
return getFallBackPage(file) || this._renderMain(null, {}, loadSideAndNav)
79+
}
80+
)
5881

5982
// Load nav
6083
loadNavbar &&

0 commit comments

Comments
 (0)