Is it possible to add a (different) identifier for each paragraph?

I wonder if, with Hugo or Goldmark, it’s possible to add a (different) identifier for each paragraph. I think that there is no option like that in Hugo, and I’m not sure that is possible with a render hook :thinking:
Sorry if the question was already been asked, I found nothing on the forum or in the Goldmark repository.
Thanks in advance for your help!

Automatically to each paragraph or manually as needed?

Are you asking for an id attribute in the p element, or something else?

Sorry I was not clear, but I mean automatically and with an id and the p element! Something like:

  • source:
First paragraph

Second paragraph
  • template:
<main>{{ .Content }}</main>
  • HTML output:
<main>
  <p id="p-01">First paragraph</p>
  <p id="p-02">Second paragraph</p>
</main>
1 Like

I’ve been looking to do this for markdown content myself. If every markdown generated content could have auto classes appended to the element class="" , like for each Goldmark generated element, do .md-content-p-1, .md-content-p-2, p-N for paragraphs, or ul-1 ul-2 etc for lists etc., prepended by something like md-content-element-number prefix etc.

If every markdown generated content could have this, things would be so much easier in so many more ways.

The more complicated way would be to use specific CSS or xPath selectors.

Like main p
main p:nth-child(1)
main p:nth-child(2)
main p:nth-child(3)

to select nth paragraph inside <main>

I definitely prefer the CSS approach if possible, but this seems to work…

In your templates, replace .Content with:

{{ $c := .Content }}
{{ range $k, $_ := findRE `<p>.*?</p>` $c }}
  {{ $paragraphId := printf "p-%03d" (add 1 $k) }}
  {{ $newParagraph := replaceRE `<p>` (printf "<p id=%q>" $paragraphId) . }}
  {{ $c = strings.Replace $c . $newParagraph 1 }}
{{ end }}
{{ $c | safeHTML}}

For a smallish site, OK. For a large site, no (performance).

2 Likes

Why would you want to do that? What’s the use case?

Thanks a lot @jmooring I will test it soon, I was not aware that this kind post-production was possible, interesting!

Yes @nternetinspired good question! I plan to assign the same text blocks to two language versions of the same text, and for prototyping that I think an ID on each paragraph will be helpful the attribution.

Not sure that CSS will figure what I want, but it would be the lightest :thinking:

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.