HUGO

Pass heading classes via Goldmark to render-heading hook

With Goldmark, I’m able to add classes to my headings via Markdown like so:

## Brave Browser{.text-center}

Is there a way that I can access that class via the context passed down to the render-heading hook? I’m not seeing any way in the docs, however I’m hoping that there’s some undocumented means of doing so.

Thanks so much!

Hello,

I don’t think that this feature is currently available in Hugo.

Perhaps others know more.

This previous work may be helpful.

1 Like

You could try specifying the classes for the headers in the front matter and render them out in the render hook.

The OP refers to this Goldmark feature:

Attributes

The parser.WithAttribute option allows you to define attributes on some elements.

Currently only headings support attributes.

Attributes are being discussed in the CommonMark forum. This syntax may possibly change in the future.

Headings

## heading ## {#id .className attrName=attrValue class="class1 class2"}

## heading {#id .className attrName=attrValue class="class1 class2"}
heading {#id .className attrName=attrValue}
============

Currently Hugo does output the class attribute from a markdown heading in the generated HTML.

In my comment above what I really meant was that I am not aware whether the markdown heading class attribute can be read from a render-heading hook template.

Here is my way of hacking around this limitation for now. I only needed classes so made it simple. Conceivably this could be expanded on to support the full range of ids, classes, and attributes values.

{{- $text := ( .Text | htmlUnescape ) -}}
{{- $class := findRE "{.+}" $text 1 -}}
{{- if $class -}}
    {{- $class = index $class 0  }}
    {{- $text = replace $text $class "" -}}
    {{- $text = trim $text " " -}}
    {{- $class = trim $class "{}" -}}
{{- end -}}
<h{{ (add .Level 1) }} id="{{ $text | anchorize | safeURL }}"{{ with $class }} class="{{ . }}"{{ end }}>{{ $text }}</h{{ (add .Level 1)
 }}>