Is there a good reason not to have a mechanism facilitating a title for code blocks?

This is minimal example of codeblock render hook:

layouts/_default/_markup/render-codeblock.html

{{ if transform.CanHighlight .Type }}
  {{/* Supported Chroma Language*/}}
  
  <div class="highlight">
  {{ with .Attributes.title }}
    <div class="highlight-title"><span>{{ . }}</span></div>
  {{ end }}
  <pre tabindex="0" class="chroma"><code class="language-{{ .Type }}" data-lang="{{ .Type }}">  
  {{- with transform.HighlightCodeBlock . -}}
    {{ .Inner }}
  {{- end -}}
  </code></pre></div>

{{ else }}
  {{/* Unsupported Language */}}
  <div class="highlight">
  {{ with .Attributes.title }}
    <div class="highlight-title"><span>{{ . }}</span></div>
  {{ end }}  
    <pre tabindex="0"><code class="language-{{ .Type }}" data-lang="{{ .Type }}">{{ .Inner }}</code></pre>
  </div>
{{ end }}

  • {{ transform.CanHighlight string }} return boolean, check if code lang supported by chroma
  • {{ transform.HighlightCodeBlock codeBlockContext }}
    • codeBlockContext is current . of render-codeblock.html template context
  • transform.HighlightCodeBlock returns .Inner and .Wrapped
    • .Inner is the highlighted code only
    • .Wrapped is the default codeblock render without custom template

NOTE: i recommend to set markup.highlight.noClasses to false and use external stylesheet, because you will use the .Inner return from transform.HighlightCodeBlock, it’s not included with the injected <pre> tag with style attribute

# config.yaml
markup:
  highlight:
    noClasses: false
3 Likes