Skip to content

Commit

Permalink
feat: ✨ auto switch language(#43)
Browse files Browse the repository at this point in the history
  • Loading branch information
Jeff-Tian authored and thonatos committed Jun 13, 2019
1 parent ef494d9 commit 82072a8
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 8 deletions.
10 changes: 5 additions & 5 deletions lib/themes/egg/layout/partial/aside.nunjucks
Original file line number Diff line number Diff line change
Expand Up @@ -47,10 +47,10 @@ mobileAside.onclick = function(e) {
const targetId = e.target.id;
if (targetId && (targetId.indexOf('title-') > -1 || targetId.indexOf('collapse-icon-') > -1)) {
const title = targetId.replace('title-', '').replace('collapse-icon-', '');
try {
// the the browser may have no localStroage or JSON.parse may throw exception.
try {
// the browser may have no localStorage or JSON.parse may throw exception.
const menuInfo = JSON.parse(window.localStorage.getItem('menuInfo'));

// current menu status
const curClosed = menuInfo[title] ? menuInfo[title].closed : false; // default false

Expand All @@ -76,8 +76,8 @@ mobileTrigger.onclick = function(e) {
(function() {
// save data to localStorage because the page will refresh when user change the url.
let menuInfo;
try {
// the the browser may have no localStroage or JSON.parse may throw exception.
try {
// the browser may have no localStorage or JSON.parse may throw exception.
menuInfo = JSON.parse(window.localStorage.getItem('menuInfo'));
if (!menuInfo) {
menuInfo = {};
Expand Down
19 changes: 16 additions & 3 deletions lib/themes/egg/scripts/helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -72,13 +72,26 @@ hexo.extend.helper.register('language_list', function() {
language.forEach(item => {
if (lanRef[item]) {
const highlight = this.page.lang === item ? 'style="color: #22ab28"' : '';
languageList += `<li><a id="${item}" href="/${item}/${this.page.canonical_path}" ${highlight}>${lanRef[item]}</a></li>`;
languageList += `<li><a onclick="rememberLang('${item}')" id="${item}" href="/${item}/${this.page.canonical_path}" ${highlight}>${lanRef[item]}</a></li>`;
}
});
languageList += '</ul>';
}

return languageList;
return languageList + `<script
type="text/javascript">
function rememberLang(lang){
localStorage.setItem('lang', lang)
}
var l = localStorage.getItem('lang') || navigator.language.toLowerCase();
var clientLanRef = ${JSON.stringify(lanRef)};
var pageLang = ${JSON.stringify(this.page.lang)};
if(location.pathname === '/' && !!clientLanRef[l] && l !== pageLang) {
location.href='/' + l + '/'
}
</script>`;
});

hexo.extend.helper.register('deer_stat', function () {
Expand All @@ -101,4 +114,4 @@ hexo.extend.helper.register('deer_stat', function () {
</script>
`;
return script;
});
});

0 comments on commit 82072a8

Please sign in to comment.