【问题标题】:prosemirror: converting JSON output into HTMLprosemiMirror:将 JSON 输出转换为 HTML
【发布时间】:2018-09-07 19:34:16
【问题描述】:

我正在尝试将 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)。 那个听起来是对的吗?任何帮助将不胜感激。

【问题讨论】:

    标签: prose-mirror


    【解决方案1】:

    经过一番挖掘,这是我如何让它工作的:

    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>

    【讨论】:

      猜你喜欢
      • 2016-08-17
      • 1970-01-01
      • 2017-02-04
      • 1970-01-01
      • 1970-01-01
      • 2017-12-31
      • 2015-07-29
      • 2017-11-19
      • 2017-08-03
      相关资源
      最近更新 更多