用于Open Graph标记的几个_document.js

时间:2017-05-17 06:26:34

标签: javascript reactjs next.js

我正在尝试实施og标记到我的网站( next.js )。

主页包含 business.business 类型和前缀

<head prefix="og: http://ogp.me/ns# fb: http://ogp.me/ns/fb# business: http://ogp.me/ns/business#">

但博客中的文章页面有文章类型和前缀

<head prefix="og: http://ogp.me/ns# fb: http://ogp.me/ns/fb# article: http://ogp.me/ns/article#">

帮助我处理头部前缀,或者是否可以使用多种 _document.js

1 个答案:

答案 0 :(得分:0)

您可以拥有一个具有动态输出的文件,而不是多个_document.js个文件。

具体来说,您可以检查传递给自定义pathnamegetInitialProps()方法的对象的_document.js属性,然后从那里确定该页面是主页还是一篇文章。

更新:这在Next.js v2.4.5(当前稳定版本)中不起作用,但在v3.0.1-beta.1 中有效。

因此,在您的情况下,它可能看起来像这样:

// ./pages/_document.js
import Document, { Head, Main, NextScript } from 'next/document'
import flush from 'styled-jsx/server'

const businessPrefix = 'og: http://ogp.me/ns# fb: http://ogp.me/ns/fb# business: http://ogp.me/ns/business#';
const articlePrefix = 'og: http://ogp.me/ns# fb: http://ogp.me/ns/fb# article: http://ogp.me/ns/article#';

export default class MyDocument extends Document {
  static getInitialProps ({ pathname, renderPage }) {
    const {html, head, errorHtml, chunks} = renderPage()
    const styles = flush()
    return { pathname, html, head, errorHtml, chunks, styles }
  }

  render () {
    return (
     <html>
       <Head prefix={this.props.pathname === '/' ? businessPrefix : articlePrefix}/>
       <body>
         <Main />
         <NextScript />
       </body>
     </html>
    )
  }
}

请参阅https://next-test-peusycafcq.now.sh/https://next-test-peusycafcq.now.sh/article的工作示例。 (在每个页面上右键单击并查看源代码以查看<head>标记中的正确前缀,请参阅https://zeit.co/KYilgchYUEorC1g8s2HO4ALi/next-test/peusycafcq/source以查看完整的源代码。)

另请参阅https://github.com/zeit/next.js/blob/3a9c419160c33613cadf3e44b0aba82767c44d3a/readme.md#custom-documenthttps://github.com/zeit/next.js/blob/3a9c419160c33613cadf3e44b0aba82767c44d3a/readme.md#fetching-data-and-component-lifecycle