【问题标题】:Several _document.js for Open Graph markupOpen Graph 标记的几个 _document.js
【发布时间】:2017-10-16 11:02:00
【问题描述】:

我正在尝试对我的网站实施 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的方法?

【问题讨论】:

    标签: javascript reactjs next.js


    【解决方案1】:

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

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

    更新:这在 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 的工作示例。 (在每个页面上右键查看源代码可以看到&lt;head&gt;标签中的正确前缀,查看完整源代码见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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-17
    • 2016-10-11
    • 2012-01-15
    • 2013-11-25
    • 2016-04-30
    • 2020-01-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多