本文共 8685 字,大约阅读时间需要 28 分钟。
gatsby
In a previous post, , I built . Kodou has a Japanese and and English version. The post was a bit long so I didn’t talk about some of the utilities I used and how to build the site’s navigation menu.
在上一篇文章“ ,我构建了 。 Kodou有日文和英文版本。 帖子过长,所以我没有谈论我使用的一些实用程序以及如何构建站点的导航菜单。
In our previous post, we built a site in Japanese and English. The site’s default language is English. This means we have two URL types:
在上一篇文章中,我们用日语和英语构建了一个网站。 该网站的默认语言是英语。 这意味着我们有两种URL类型:
The Japanese pages: kodou.me/ja/team
日语页面: kodou.me/ja/team
The English pages kodou.me/team
英文页面kodou.me/team
The different page versions are written in . We make Gatsby aware of the languages we use in /config/languages
. In gatsby-node.js
, we create our pages by using templates which we populate with data from Cosmic JS.
不同的页面版本使用编写。 我们让盖茨比知道/config/languages
使用的/config/languages
。 在gatsby-node.js
,我们使用模板填充模板,这些模板填充了Cosmic JS中的数据。
Here’s a simplified version of what the team-members
array returned by Cosmic JS might look like.
这是Cosmic JS返回的team-members
数组的简化版本。
teamMembers = [ { title: 'CEO', fullName: 'Jack Misteli', content: 'The CEO of the Company', locale: 'en' }, { title: 'CEO', fullName: 'ジャック・ミステリ', content: '会社のCEO', locale: 'ja' }]
After we received the teamMembers
we create two objects jaTeamMembers
and enTeamMembers
. We populate templates/team
with jaTeamMembers
to create /ja/team
and enTeamMembers
to create /team
.
我们收到后teamMembers
我们创建了两个对象jaTeamMembers
和enTeamMembers
。 我们使用jaTeamMembers
填充templates/team
来创建/ja/team
并使用enTeamMembers
来创建/team
。
It’s important to be a good web citizen and make the sites we create accessible. So the first thing we need to do is add our languages to our site’s metadata. It might also help you get more targeted search results.
成为一个好的网络公民并让我们创建的网站变得可访问非常重要。 因此,我们需要做的第一件事就是将语言添加到网站的元数据中。 它还可以帮助您获得更有针对性的搜索结果。
module.export = { siteMetadata: { title: `Kodou`, description: `Kodou site description`, author: `Jack Misteli `, languages }, //....
In our Gatsby application we also pass down to our templates the current language in the page’s context.
在我们的Gatsby应用程序中,我们还将页面上下文中的当前语言传递给模板。
// langs contains the languages of our blog and default langKey is the default language of the site// To be fully programmatic we could calculate langs// here langs = ['en', 'ja'] and defaultLangKey = 'en'const { langs, defaultLangKey } = require('../config/languages')const path = require(`path`)const { localizeUrl, createLanguagesObject } = require('../utils/localization')module.exports = async (options, createPage, graphql) => { const {query, pageName} = options let templateName = options.templateName ? options.templateName : pageName const result = await graphql(query) if (result.errors) console.error(result.errors) const cosmicJSData = createLanguagesObject(langs) Object.values(result.data)[0].edges.forEach(({ node }) => { cosmicJSData[node.locale].push(node) }) // we create a new page for each language langs.forEach(lang => { createPage({ // the localizeUrl function creates a url which takes into consideration what the default language is path: localizeUrl(lang, defaultLangKey, '/team'), component: path.resolve(`src/templates/team.js`), context: { profiles: profiles[lang], // Here we pass the current language to the page lang } }) })}
Now we can access lang
in our templates
现在我们可以在模板中访问lang
const { lang } = props.pageContext;
The is used for string comparison, number formatting, and date and time formatting. It has a lot of cool features which we won’t explore here. We will simply use it here to display dates in the appropriate format.
用于字符串比较,数字格式以及日期和时间格式。 它具有很多很酷的功能,我们在这里将不介绍。 我们将在这里仅使用它以适当的格式显示日期。
We are adding the react-intl
package in our Layout
file.
我们正在Layout
文件中添加react-intl
包。
import React from "react"import { useStaticQuery, graphql } from "gatsby"import "../styles/main.scss"import Header from "./header"import { IntlProvider, FormattedDate } from "react-intl"const Layout = ({ children, location, lang }) => { // We populated the siteMetaData in `gatsby-config.js` and are extracting it here for some extra language context // The best practice here would be to directly get that data from `config` but I want to show different ways to do it const data = useStaticQuery(graphql` query SiteInfoQuery { site { siteMetadata { title languages { defaultLang langs } } }} `) // langs is an array of all the supported languages // defaultLang is the default site language // title is the website's title const {langs, defaultLang, title} = data.site.siteMetadata return ( // We use IntlProvider to set the default language of our page)}export default Layout {children}
When the page is generated in English, <FormattedDate>
will return Monday, December 9, 2019
. When the page is generated in Japanese <FormattedDate>
will return 2019年12月9日月曜日
.
用英语生成页面时, <FormattedDate>
将返回Monday, December 9, 2019
。 用日语生成页面时, <FormattedDate>
将返回2019年12月9日月曜日
。
You can see that in Layout
we have a Header
component. We pass all the language information to the header except the current language prop. We don’t pass it because I want to show you another way to the page’s current language.
您可以看到在Layout
我们有一个Header
组件。 我们将所有语言信息传递给标头(当前语言道具除外)。 我们没有通过它,因为我想向您展示该页面当前语言的另一种方式。
import { Link } from "gatsby"import PropTypes from "prop-types"import React from "react"import { getCurrentLangKey, getLangs, getUrlForLang } from 'ptz-i18n'import langmap from 'langmap'import { localizeUrl, buildMenu } from '../../utils/localization'const Header = ({ languages, location, defaultLang}) => { const url = location.pathname const currentLangKey = getCurrentLangKey(languages, defaultLang, url) // Create a home link by adding a slash before the language and if it const homeLink = localizeUrl(currentLangKey, defaultLang, '/') // Get langs return language menu information // langsMenu will allow us to build a dropdown with all the available language options const langsMenu = buildMenu(languages, defaultLang, currentLangKey, url) // On the `/team` page this will return the following array // [{selected: true, link: "/team/", langKey: "en"}, // {selected: false, link: "/ja/team/", langKey: "ja"}] // All the navigation menu item titles const allLanguageTitles = { 'en':['Concept', 'Work', 'Team', 'News', 'Contact'], 'ja': ['コンセプト', '仕事', 'チーム', 'ニュース', '連絡先'] } // Selecting the current language and default to english titles const currentLanguageTitles = allLanguageTitles[currentLangKey] || allLanguageTitles['en'] // allNavigationLinks contains all the pages name, with urls in every supported language const allNavigationLinks = currentLanguageTitles.map((page, i) => ({ name: page, url: `${homeLink.replace(defaultLang, '')}${allLanguageTitles.en[i].toLowerCase()}` })) // On the English page it will return // [{name: "Concept", url: "/concept"}, {name: "Work", url: "/work"}, {name: "Team", url: "/team"}...] // [{name: "コンセプト", url: "/ja/concept"}, {name: "仕事", url: "/ja/work"}, {name: "チーム", url: "/ja/team"} ...] return ( )}export default Header
And that’s it, you have a navigation menu in different languages which adapts its links according to the user’s current language. If you want to check out the utility functions I built they are available in .
就是这样,您有一个使用不同语言的导航菜单,该菜单会根据用户当前的语言来调整其链接。 如果您想查看我构建的实用程序功能,可以在中找到它们。
翻译自:
gatsby
转载地址:http://mshgb.baihongyu.com/