prosemirror:将JSON输出转换为HTML

时间:2018-09-07 19:34:17

标签: prose-mirror

我正在尝试将ProseMirror的JSON输出转换回HTML(以将其从一个数据库保存到另一个数据库)。我是ProseMirror的新手,我不确定我是否完全了解模型,状态和架构之间的关系。

从我读过的https://github.com/ProseMirror/prosemirror/issues/455https://discuss.prosemirror.net/t/example-of-converting-between-formats-for-the-purpose-of-saving/424来看,

我应该首先基于基本架构创建一个新状态,然后使用DOMSerializer并将输出附加到一个临时元素(然后获取innerHtml)。 那个听起来是对的吗?任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

经过一些挖掘,这是我如何使其工作的方法:

  1. 使用.fromJSON创建节点
  2. 根据编辑器使用的模式制​​作DOMSerializer
  3. 将节点传递给序列化器

我的代码在下面。

const { schema } = require("prosemirror-schema-basic")
const { Node, DOMSerializer } = require("prosemirror-model")
const jsdom = require("jsdom").JSDOM

let dom = new jsdom('<!DOCTYPE html><div id="content"></div>')
let doc = dom.window.document
let target = doc.querySelector("div")
//Demo JSON output from ProseMirror
let content = {
  "doc": {
    "type": "doc",
    "content": [{
      "type": "paragraph",
      "attrs": {
        "align": "left"
      },
      "content": [{
        "type": "text",
        "text": "My sample text"
      }]
    }]
  },
  "selection": {
    "type": "text",
    "anchor": 16,
    "head": 16
  }
}

let contentNode = Node.fromJSON(schema, content.doc)

DOMSerializer
  .fromSchema(schema)
  .serializeFragment(contentNode.content, {
    "document": doc
  }, target)

console.log(doc.getElementById("content").innerHTML)
//<p>My sample text</p>