Code Now

如何让hugo支持infographic

· LuYanFCP

前言

infographic 是蚂蚁Antv的新组建,其目标是为AI提供更易用的可视化工具,定位类似于mermaid。其提供了开发者/AI易用的DSL,通过快捷的编写DSL就可以很快的快速可视化,各种图表例如折线图/饼图之类的,同时也可以可视化一些类似于PPT需要使用到的grid图/swot图之类的工具,非常的易用。因此我希望可以引入我的hugo博客,并且可以通过markdown code block快速的通过infographic 可视化我的想法。

怎么做?

Hugo提供了embedded code block render hook. 可以通过模版对特定的language的 code block进行渲染,Hugo中的Mermaid等图都可以使用这种方法。

step1: 增加js import

在全局header中增加对infographic的包的引用,可以在 layouts/partials/foot_custom.html 增加对AntV Infographic的引用

1<script src="https://unpkg.com/@antv/infographic@latest/dist/infographic.min.js"></script>

step2: 增加自定义渲染block的hook

  1. 增加layouts/_default/_markup/render-codeblock-infographic.html
  2. 通过模版和js脚本对整体html进行渲染和注入
 1<div id="infographic-{{ .Ordinal }}" class="infographic-container" style="min-height: 500px; width: 100%;"></div>
 2<script>
 3(function() {
 4  const container = document.getElementById('infographic-{{ .Ordinal }}');
 5  const syntax = `{{ .Inner | safeJS }}`;
 6  
 7  function renderInfographic() {
 8    if (window.AntVInfographic) {
 9      const { Infographic } = window.AntVInfographic;
10      const infographic = new Infographic({
11        container: container,
12        width: '100%',
13        height: '500px',
14      });
15      infographic.render(syntax);
16    } else {
17      // Retry if library not loaded yet
18      setTimeout(renderInfographic, 100);
19    }
20  }
21  
22  if (document.readyState === 'complete') {
23    renderInfographic();
24  } else {
25    window.addEventListener('load', renderInfographic);
26  }
27})();
28</script>
29{{ .Page.Store.Set "hasInfographic" true }}

效果

example1: 基础图

example2: 架构图


查看原始Issue