通过gatsby-config + gatsby-source-wordpress中的规范化函数解码HTML实体的解决方案。

问题描述 投票:1回答:1

这应该是很容易的,但我努力让这个工作... ...

我用的是 gatsby-source-wordpress 来将博客内容拉到我的gatsby网站。问题是HTML实体没有被解码,所以我看到的不是'&'字符,而是类似'&8466;'的东西。

我想在我的应用程序中实现一个规范化的函数。gatsby-config.js 文件。

我在网上找到了这个功能,应该可以解决HTML实体的问题。

const decodeHTML = ({input}) => {
    let txt = document.createElement('textarea');
    txt.innerHTML = input;
    return txt.value;
}

我试着把它导入到我的 gatsby-config.js 从一个单独的文件中提取;我也直接将函数放在了 gatsby-config.js 文件。理想情况下,我想从一个单独的项目文件中导入这个函数,但这不是主要问题。

为了让这个函数工作,我直接把它内联到了配置文件中。

{
  resolve: `gatsby-source-wordpress`,
  options: {
    baseUrl: `peakwebsites.ca`,
    protocol: `https`,
    useACF: false,
    verboseOutput: false,
    hostingWPCOM: false,
    normalizer: function decodeHTML({entities}) {
      let txt = document.createElement('textarea');
      txt.innerHTML = entities;
      return txt.value;
    }
  }
},

但我遇到了这个错误

success Downloading remote files - 7.158s - 205/205 28.64/s

 ERROR #11321  PLUGIN

"gatsby-source-wordpress" threw an error while running the sourceNodes lifecycle:

Cannot read property 'forEach' of undefined

  299 |       createNode,
  300 |       createContentDigest
> 301 |     }) => normalize.createNodesFromEntities({
      |                     ^
  302 |       entities,
  303 |       createNode,
  304 |       createContentDigest


 File: node_modules\gatsby-source-wordpress\gatsby-node.js:301:21

我不是很熟悉Wordpress源码插件的内部工作原理 所以可能有一些对象属性需要我去解析。我真的不清楚。

有谁有办法通过gatsby-config中的规范化函数来解码HTML实体?

谢谢。

gatsby normalize
1个回答
1
投票

我不熟悉gatsby-source-wordpress,但我觉得我有足够的信息让你走上正确的道路。

  1. 你将无法访问 document 从gatsby-config.js,它运行在Nodejs环境下。使用node库来代替,快速搜索一下 翘起 he.
const he = require('he')

const decode = input => he.decode(input)
  1. 快速查看一下gatsby-source-wordpress的文档,就会发现 entities 是一个数组。我不知道它的形状是什么样子的,你要登录出来才能看到它是什么。一旦你知道如何访问你的HTML文本,你可以使用上面的解码功能。
{
  resolve: 'gatsby-source-wordpress',
  options: {
    // ...other options
    normalizer: ({ entities }) => entities.map(entity => {
      /* access your raw html somehow, this is just a guess */
      if (entity.__type === 'wordpress_post_or_something') {
        entity.content = decode(entity.content)
      }
      return entity
    })
  } 
}


或者,你也可以在gatsby-source-wordpress创建的节点上添加一个新的字段,通过... ... createNodeFieldonCreateNodecreateSchemaCustomization. 我们的想法是从节点中获取html内容,进行解码,然后将其作为一个新的字段添加回该节点。

如果有更熟悉wordpress的人可以帮忙,我很乐意删除更新这个答案。

© www.soinside.com 2019 - 2024. All rights reserved.