Используя Gatsby.js, как добавить метатег og: image для конкретного маршрута? - PullRequest
0 голосов
/ 03 мая 2018

Я уже настроил изображение общего доступа для своего корневого маршрута в React Helmet со следующим кодом:

<meta property="og:url" content="https://foo.com" />
<meta property="og:image" content="https://myhostedimg.png" />

У меня есть отдельный маршрут или «страница» в Гэтсби, для которого я хочу установить другое значение og:image. Поскольку нет ничего связывающего og:image с og:url, как мне указать пользовательские ссылки og:url и og:image на моих страницах?

1 Ответ

0 голосов
/ 03 мая 2018

Вариант 1. Вы можете выполнить анализ маршрута в своем основном файле layout, а затем передать два объекта (один для изображения, один для маршрута) в любой компонент, контролирующий ваши метаданные.

В этом примере мой компонент метаданных называется metadata, но он должен иметь смысл независимо от структуры вашего компонента:

// Setup react stuff
import React from 'react'
import PropTypes from 'prop-types'

// Get your custom gatsby components - assuming a pretty basic layout here
import Metadata from '../components/Metadata'
import Header from '../components/Header'
import Footer from '../components/Footer'

// Get images you want, also assuming you have these in a static folder and you don't need to use `gatsby-image` to get them
import ogImgOne from './og-img-one.png'
import ogImgTwo from './og-img-two.png'

// Setup template wrapper
export default class TemplateWrapper extends React.Component {

  // We want to render different base templates depending on the path the user hits
  render() {

    // Page 1
    if (this.props.location.pathname === "/") {
      return (
        <div className="page1">
          <Header />
          <Metadata ogImgSrc={ ogImgOne } 
                    ogUrl={ this.props.location.pathname } />
          <div>
            { this.props.children() }
          </div>
          <Footer />
        </div>
      )
    } 

    // Page 2
    if (this.props.location.pathname === "/page-2/") {
      return (
        <div className="page2">
          <Metadata ogImgSrc={ ogImgTwo } 
                    ogUrl={ this.props.location.pathname } />
          <Header />
          <div>
            { this.props.children() }
          </div>
          <Footer />
        </div>
      )
    }
  }
}

Вариант 2 просто использует React Helmet , который входит в комплект поставки Gatsby "из коробки" (по крайней мере, начиная с v2.x). В этой настройке вы можете установить компонент метаданных, который использует шлем, а затем легко переопределить эти предустановки на страницах Gatsby. Шлем будет переопределять только те элементы метаданных, которые вы указали, оставляя другие, если они не нуждаются в настройке. Просто импортируйте / вызывайте Helmet на своей странице / компоненте для простых переопределений:

metadata.js:

import React from 'react'
import Helmet from 'react-helmet'

import icon from '../../images/logo.png'
import socialBanner from '../../images/PFB_2018_social.jpg'

const Metadata = () => (
  <div>
    <Helmet>
      <title>Whatever</title>

      <meta property='og:image' content={ socialBanner } />
      <meta property='og:locale' content='en_US' />
      <meta property='og:type' content='website' />
      <meta property='og:title' content='Whatever' />
      <meta property='og:description' content="Description" />
      <meta property='og:url' content='https://example.org' />
      <meta property='og:updated_time' content='2019-01-31' />
    </Helmet>
  </div>
)

export default Metadata

страница-example.js:

import React from 'react'
import Helmet from 'react-helmet'

export default class Example extends React.Component {
  render() {
    return (
      <div>

            {/* Custom metadata - assuming something coming from Node.js in pageContext prop */}
            <Helmet>
              <title>Override here</title>

              { /* Example from pageContext prop, gatsby-node.js */}
              <meta property='og:title' content={ `${this.props.pageContext.title} | Your brand` } />

              { /* Image from gatsby-node.js example, using gatsby-image for override */}
              <meta property='og:image' content={ this.props.pageContext.images[0].localFile.childImageSharp.fluid.src } />

              { /* Get path from location string */}
              <meta property='og:url' content={ this.props.location.href } />

            </Helmet>
      </div>
    )
  }
}
...