Linvis Blog

Hexo的多语言配置

2019-05-16

关于Hexo的中英文语言配置,我的做法是,在菜单栏添加一个按键,通过按键切换到中/英文界面,让中文文章只显示在中文页面,英文显示在英文页面。

插件安装

首先,安装hexo-generator-i18n插件

1
$ npm install hexo-generator-i18n --save

然后修改_config.yml

1
2
3
4
5
6
# 需修改Hexo默认的空值为确切的语言列表,记得在主题languages目录下添加对应的语言.yml文件
language: [zh-CN,en]
# hexo-generator-i18n 选项(可选,默认使用如下设置)
i18n:
type: [page, post]
generator: [index, archive, category, tag]

这里并没有明白tyte和generator的作用,但是似乎不影响

之后是在主题languages目录下添加对应的语言.yml文件(如zh.yml, en.yml)

但是由于我使用的主题并不支持多语言,我也懒得弄,所有暂时没有管这一项

插件安装完成后,执行hexo clean & hexo g

会生成public/en目录,对于_post内的所有博文,都会在public里存放一份,en下存放一份。

那么就需要根据页面的语言,显示不同的博文。

博文配置

对于所有的markdown文章,都需要在文章内添加属性lang:zh-CN or lang:en,来区分中英文

网页配置

我通过url来区分中英文页面,对于中文,url是www.yoursite.com,英文,url是www.yoursite.com/en/,

这样,在js中检索url是否包含en,来判断显示中文还是英文界面。

修改主题, 我的主题路径是themes/vexo/layout/index.ejs

获取当前html的路径,并判断路径内是否存在en

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
<main class="app-body">
<% var currentURL = page.path.split('/') %>
<% if (currentURL.length === 1) { %>
<% var lang = page.lang %>
<% } else { %>
<% var lang = currentURL.shift() %>
<% } %>
<% page.posts.each(function(post) { %>
<% if (lang == post.lang) { %>
<article class="article-card">
<h2 class="article-head">
<a href="<%- url_for(post.path) %>"><%- post.title %></a>
</h2>
<p class="article-date"><%- date(post.date, "LL") %></p>
<% if (post.tags && post.tags.length) { %>
<%- partial('_partial/tag', { tags: post.tags }) %>
<% } %>
<div class="article-summary">
<% if (post.excerpt) { %>
<%- post.excerpt %>
<% } else { %>
<%- truncate(strip_html(post.content), { length: 150, omission: ' ...' }) %>
<% } %>
</div>
<a class="more" href="<%- url_for(post.path) %>"><%- theme.excerpt_link %></a>
</article>
<% } %>
<% }) %>

<% if (page.total > 1){ %>
<%- partial('_partial/pager') %>
<% } %>
</main>

上述都完成,就可以通过www.yoursite.com/en进入英文网页,且该网页只有英文文章

添加切换语言按钮

修改theme下的_config.yml文件, 添加一个EN的按钮,跳转到英文界面

1
2
3
4
5
6
7
menu:
Home: /
Tags: /tags/
Archives: /archives/
Projects: /project/
About: /about/
EN: /en/

这里为了简单,没有动态修改EN这个按钮,提供从英文网页,跳转回中文网页的方式(实际上,点击Home按键,就跳转回中文了)

部署测试

1
2
hexo clean & hexo g
hexo d

这里只配置了主页,其他页面暂时没有修改

扫描二维码,分享此文章