Diagrams

Use a fenced code block to embed an SVG image of a diagram in your Hugo site using the free Kroki service. Unlike JavaScript solutions that require client-side rendering, this approach embeds an SVG image in your page.

Overview

Kroki generates diagrams from textual descriptions, and provides a unified API with support for D2, Mermaid, PlantUML, and other diagram types.

You can create:

Visit the Kroki site for more examples.

Examples

D2

This is an example of a D2 diagram.

```kroki {type=d2}
# Actors
hans: Hans Niemann

defendants: {
  mc: Magnus Carlsen
  playmagnus: Play Magnus Group
  chesscom: Chess.com
  naka: Hikaru Nakamura

  mc -> playmagnus: Owns majority
  playmagnus <-> chesscom: Merger talks
  chesscom -> naka: Sponsoring
}

# Accusations
hans -> defendants: 'sueing for $100M'

# Offense
defendants.naka -> hans: Accused of cheating on his stream
defendants.mc -> hans: Lost then withdrew with accusations
defendants.chesscom -> hans: 72 page report of cheating
```
diagram

PlantUML

This is an example of a PlantUML mind map.

```kroki {type=plantuml}
@startmindmap
skinparam monochrome true
+ OS
++ Ubuntu
+++ Linux Mint
+++ Kubuntu
+++ Lubuntu
+++ KDE Neon
++ LMDE
++ SolydXK
++ SteamOS
++ Raspbian
-- Windows 95
-- Windows 98
-- Windows NT
--- Windows 8
--- Windows 10
@endmindmap
```
diagram

The knowledge map article contains a more complex example.

Global HTML attributes

You may also add global HTML attributes such as class and id to the SVG image.

```kroki {type=plantuml .my-class #my-id}
@startmindmap
  ...
@endmindmap
```

Source code

layouts/_default/_markup/render-codeblock-kroki.html
{{- /* Last modified: 2024-10-21T09:49:45-07:00 */}}

{{- /*
Copyright 2023 Veriphor, LLC

Licensed under the Apache License, Version 2.0 (the "License"); you may not
use this file except in compliance with the License. You may obtain a copy of
the License at

https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations under
the License.
*/}}

{{- /*
Renders an SVG image of a diagram from a textual description using the Kroki service.

References:

- https://kroki.io/
- https://kroki.io/#examples

@context {map} Attributes The Markdown attributes from the info string.
@context {string} Inner The content between the leading and trailing code fences, excluding the info string.
@context {map} Options The highlighting options from the info string.
@context {int} Ordinal The zero-based ordinal of the code block on the page.
@context {page} Page A reference to the page containing the code block.
@context {text.Position} Position The position of the code block within the page content.
@context {string} Type The first word of the info string.

@param {string} Attributes.type The type of diagram to render

@returns {template.html}
*/}}

{{- /* Initialize. */}}
{{- $renderHookName := "kroki" }}

{{- /* Verify minimum required version. */}}
{{- $minHugoVersion := "0.136.3" }}
{{- if lt hugo.Version $minHugoVersion }}
  {{- errorf "The %q code block render hook requires Hugo v%s or later." $renderHookName $minHugoVersion }}
{{- end }}

{{- /* Get context. */}}
{{- $attrs := .Attributes }}
{{- $inner := .Inner | strings.TrimSpace }}
{{- $ordinal := .Ordinal }}
{{- $position := .Position }}

{{- /* Initialize. */}}
{{- $apiEndpoint := "https://kroki.io/" }}
{{- $diagramType := $attrs.type | lower }}

{{- /* Validate diagram type. */}}
{{- $supportedTypes := slice
  "actdiag" "blockdiag" "bpmn" "bytefield" "ditaa" "d2" "dbml" "erd"
  "excalidraw" "graphviz" "mermaid" "nomnoml" "nwdiag" "packetdiag" "pikchr"
  "plantuml" "rackdiag" "seqdiag" "structurizr" "svgbob" "symbolator" "tikz"
  "umlet" "vega" "vegalite" "wavedrom" "wireviz"
}}
{{- $typesDelimited := delimit $supportedTypes ", " ", and " }}
{{- if not (in $supportedTypes $diagramType) }}
  {{- errorf "The %q code block render hook does not support diagram type %q. Valid types are %s. See %s" $renderHookName $attrs.type $typesDelimited $position }}
{{- end }}

{{- /* Determine class attribute. */}}
{{- $class := printf "diagram diagram-kroki diagram-kroki-%s" $diagramType }}
{{- with $attrs.class }}
  {{- $class = printf "%s %s" $class . }}
{{- end }}

{{- /* Determine id attribute. */}}
{{- $id := printf "h-rh-cb-kroki-%d" $ordinal }}
{{- with $attrs.id }}
  {{- $id = . }}
{{- end }}

{{- /* Merge class and id attributes. */}}
{{- $attrs = merge $attrs (dict "class" $class "id" $id "alt" "diagram") }}

{{- /* Get diagram. */}}
{{- $body := dict "diagram_source" $inner "diagram_type" $diagramType "output_format" "SVG" | jsonify }}
{{- $opts := dict "method" "post" "body" $body }}
{{- with resources.GetRemote $apiEndpoint $opts }}
  {{- with .Err }}
    {{- errorf "The %q code block render hook was unable to get the remote diagram. See %s. %s" $renderHookName $position . }}
  {{- else }}
    {{- $attrs = merge $attrs (dict "src" .RelPermalink) }}
  {{- end }}
{{- else }}
  {{- errorf "The %q code block render hook was unable to get the remote diagram. See %s" $renderHookName $position }}
{{- end }}

{{- /* Render. */}}
<img
  {{- range $k, $v := $attrs }}
    {{- if not (eq $k "type") }}
      {{- if $v }}
        {{- printf " %s=%q" $k (string $v) | safeHTMLAttr }}
      {{- end }}
    {{- end }}
  {{- end -}}
>
{{- /**/ -}}

To make the diagram responsive, add this to your CSS or Sass:

img.diagram {
  height: auto;
  width: 100%;
}

Performance

The render hook above calls Hugo’s resources.GetRemote function to request the SVG image from the Kroki API. Hugo caches the result, and invalidates the cache when (a) you edit the diagram markup, or (b) the cache expires.

To optimize performance in a CI/CD environment such as Cloudflare Pages, GitHub Pages, or Netlify, you should:

  1. Edit your site configuration to store the getresource cache in the project’s resources directory, setting the cache to never expire:

    [caches.getresource]
    dir = ':resourceDir/_gen'
    maxAge = -1
  2. Check the resources directory into source control, or limit source control to the subdirectory containing the remote resources, resources/_gen/getresource.

In this configuration, Hugo will use the cached resources when building your site locally and remotely, invalidating the cache when you change the diagram markup.

Last modified: