跳到正文

配置对象

当您自定义 Markdoc 时,必须将自定义内容传入渲染流程。最常见的方式是在渲染的 转换 阶段提供一个配置对象。

例如,创建一个配置对象,指定变量 $version 的值为 "1.0"。然后将其传递给 transform 函数。

/** @type {import('@markdoc/markdoc').Config} */
const config = { variables: { version: "1.0" }};
const ast = Markdoc.parse("This is version {% $version %}");
const content = Markdoc.transform(ast, config);
const html = Markdoc.renderers.html(content);

选项

此表格概述了可在配置对象中传递的各种选项。

类型描述
节点{ [nodeType: NodeType]: Schema }在您的模式中注册 自定义节点
标签{ [tagName: string]: Schema }在您的模式中注册 自定义标签
变量{ [variableName: string]: any }注册 变量 以在文档中使用
函数{ [functionName: string]: ConfigFunction }注册 自定义函数 以在文档中使用
部分{ [partialPath: string]: Ast.Node }注册可重用内容片段,供 partial 标签 使用

完整示例

以下是 Markdoc 配置的示例:

/** @type {import('@markdoc/markdoc').Config} */
const config = {
  nodes: {
    heading: {
      render: 'Heading',
      attributes: {
        id: { type: String },
        level: { type: Number }
      }
    }
  },
  tags: {
    callout: {
      render: 'Callout',
      attributes: {
        title: {
          type: String
        }
      }
    }
  },
  variables: {
    name: 'Dr. Mark',
    frontmatter: {
      title: 'Configuration options'
    }
  },
  functions: {
    includes: {
      transform(parameters, config) {
        const [array, value] = Object.values(parameters);

        return Array.isArray(array) ? array.includes(value) : false;
      }
    }
  },
  partials: {
    'header.md': Markdoc.parse(`# My header`)
  }
};

const content = Markdoc.transform(ast, config);