博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
gatsby_Gatsby.js中的国际化导航菜单
阅读量:2506 次
发布时间:2019-05-11

本文共 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有日文和英文版本。 帖子过长,所以我没有谈论我使用的一些实用程序以及如何构建站点的导航菜单。

快速总结 (Quick Summary)

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我们创建了两个对象jaTeamMembersenTeamMembers 。 我们使用jaTeamMembers填充templates/team来创建/ja/team并使用enTeamMembers来创建/team

使您的网站了解语言 (Making Your Site Language-Aware)

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: gatsby-config.js
模组:gatsby-config.js
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应用程序中,我们还将页面上下文中的当前语言传递给模板。

Module: pageGenerator.js
模块:pageGenerator.js
// 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;

使用国际化API (Using the Internationalization API)

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包。

Module: layout.js
模块:layout.js
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    
{children}
{/* FormattedDate will format our date according to the language we set in IntlProvider locale prop */} ©
, Built by
Jack Misteli
)}export default Layout

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日月曜日

创建菜单 (Creating a Menu)

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/

你可能感兴趣的文章
图像滤镜艺术---图像滤镜晕影调节算法研究
查看>>
Win8Metro(C#)数字图像处理--2.21二值图像腐蚀
查看>>
MVC5 + EF6 入门完整教程
查看>>
SQL Server如何在变长列上存储索引
查看>>
Replication的犄角旮旯(八)-- 订阅与发布异构的问题
查看>>
Sliverlight实例之 绘制扇形和环形图
查看>>
Visual Studio 2012使用水晶报表Crystal Report
查看>>
你不知道的 页面编码,浏览器选择编码,get,post各种乱码由来
查看>>
SQLSERVER PRINT语句的换行
查看>>
Windows 8.1 应用开发 – 触控操作
查看>>
PowerDesigner创建物理模型
查看>>
使用Git、Git GUI和TortoiseGit
查看>>
vue---canvas实现二维码和图片合成的海报
查看>>
检查项目里是否有IDFA的方法
查看>>
64位系统使用Access 数据库文件的彻底解决方法
查看>>
注释,字符串
查看>>
性能瓶颈
查看>>
cmd 导入数据库
查看>>
Makefile书写注意事项--个人择记(一)
查看>>
文件转码重写到其他文件
查看>>