add a switch language button layouts/partials/sidebar/left.html
<liid="lang-switcher">
{{ range .Site.Languages }}
<adata-url="{{ .Lang | relURL }}"href="javascript:void(0);"class="lang-item {{ if eq .Lang $.Site.Language.Lang }}active{{ end }}">
{{ .LanguageName }}
</a>
{{ end }}
</li>
add js script(It is used to automatically jump to the corresponding language homepage based on the language selected by the user)
<scriptconstlangOptions={{.Site.Languages}}.map(l=>l.Lang)constlangStoreKey='__lang__';constdefaultLang='zh';consthomePages=langOptions.map(l=>`/${l}`).concat('/');document.addEventListener('DOMContentLoaded',function(){initLangHomePage();listenLangSwitchEvent()});functionlistenLangSwitchEvent(){constcurrentLang=localStorage.getItem(langStoreKey);constcurrentPathList=window.location.pathname.split('/').filter(v=>v.length>0);document.querySelectorAll('#lang-switcher a').forEach(link=>{link.onclick=function(){letlang=this.getAttribute('data-url').replace('/','');localStorage.setItem(langStoreKey,lang);// /{currentLang?}/posts/xxx => /{lang?}/posts/xxx
constlangRedirectPathList=Array.from(currentPathList);if(langOptions.includes(langRedirectPathList[0])){langRedirectPathList[0]=lang;}else{langRedirectPathList.unshift(lang);}if(langRedirectPathList[0].includes(defaultLang)){langRedirectPathList.shift();}langRedirectPathList.unshift('');langRedirectPathList.push('');window.location.href=langRedirectPathList.join('/');};});}functioninitLangHomePage(){constcurrentPath=window.location.pathname;if(!homePages.includes(currentPath)){return;}constredirectPath=getInitRedirectPath('zh')console.log(`redirect:${redirectPath}`);if(redirectPath!==currentPath){window.location.href=redirectPath;}}functiongetInitRedirectPath(){letlang=localStorage.getItem(langStoreKey);if(lang===null){// from default browser language
lang=navigator.language.substring(0,2);}letmapLang=langOptions[0];constindex=langOptions.findIndex(l=>l.includes(lang))if(index>=0){mapLang=langOptions[index];}letredirectPath=`/${mapLang}`;if(mapLang.includes(defaultLang)){redirectPath='/';}returnredirectPath;}</script>
Translate content
The corresponding categories, labels, and contents can be named according to the rules (for example, ‘index.md’, copy a file and name it ‘index.en.md’).
For now, GPT will automatically translate all the content on my blog
<?php$rootDir=__DIR__.'/content/posts';$dir=opendir($rootDir);$postsDir=[];while(($filename=readdir($dir))!==false){if($filename!=="."&&$filename!==".."){$postsDir[]=$filename;}}info(sprintf("total dir: %d",count($postsDir)));foreach($postsDiras$i=>$dir){$index="{$rootDir}/$dir/index.md";$enIndex="{$rootDir}/$dir/index.en.md";if(!file_exists($index)){info("error {$index}");continue;}if(file_exists($enIndex)){info("exists {$enIndex} skip");continue;}$content=file_get_contents($index);$res=chat($content);$len=strlen($res);if($len>0){file_put_contents($content,$enIndex);}info("{$i} success [{$len}]{$enIndex} skip");}functioninfo($msg){echo$msg.PHP_EOL;}functionchat($content,$model='gpt-40'){$apiKey="YOUR_OPENAI_API_KEY";$endpoint='https://api.openai.com/v1/chat/completions';$data=["messages"=>[["role"=>"system","content"=>"According to the hugo format, translate the title, description, tags and content of the file into English. When encountering professional terms or those in English, skip these keywords"],["role"=>"user","content"=>$content]],"model"=>$model,];$headers=array('Content-Type: application/json','Authorization: Bearer '.$apiKey);$ch=curl_init();curl_setopt($ch,CURLOPT_URL,$endpoint);curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);curl_setopt($ch,CURLOPT_HEADER,false);curl_setopt($ch,CURLOPT_FOLLOWLOCATION,true);curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);curl_setopt($ch,CURLOPT_HTTP_VERSION,CURL_HTTP_VERSION_1_1);curl_setopt($ch,CURLOPT_POSTFIELDS,json_encode($data,JSON_UNESCAPED_UNICODE));curl_setopt($ch,CURLOPT_HTTPHEADER,$headers);$response=curl_exec($ch);curl_close($ch);$decodedResponse=json_decode($response,true);$ret='';if(isset($decodedResponse['choices'][0]['message']['content'])){$ret=$decodedResponse['choices'][0]['message']['content'];}return$ret;}