Add template logic between content and its footnotes

Hello,

This is a question regarding theme development.

I use Markdown/Goldmark to format and process my content, and it outputs a fancy html that I call by adding {{ .Content }} within layouts/single.html. Well, but how can I add template logic between the content and the footnotes, as these two things are built as a whole in this unique variable: {{ .Content }}?

To be more concrete, this is what I’d like to achieve:

<!-- Generated content -->
<p>...</p>

<div id="my_template_logic">
    ...
</div>

<!-- Generated footnotes -->
<section class="footnotes" role="doc-endnotes">...</section>

So, its not conceivable to add a shortcode (e.g. {{% my_template_logic %}}{{% /my_template_logic %}}) in each markdown-formatted article to put logic in the right place; this is obviously not maintainable. Ideally, the solution should use Hugo’s ability to handle this scenario inside theme’s scope; CSS/Javascript tricks would be a last chance solution.

Is there a clean solution to achieve this?

One way of splitting the .Content variable would be to use conditional logic with the strings.Contains method along with the split and index functions.

The following is untested but it might work.

{{/* store the beginning of the footnotes specific HTML generated by the Markdown processor into a variable */}}
{{ $footnotes:= `<section class="footnotes" role="doc-endnotes">` }}
{{ if strings.Contains .Content $footnotes }}
{{/* split content and store the result into a variable */}}
{{ $split := split .Content $footnotes }}
{{/* render content before footnotes */}}
{{ index $split 0 | safeHTML }}
<! -- fancy HTML --!>
{{/* render footnotes */}}
{{ index $split 1 | safeHTML }}
{{ else }}
{{ .Content }}
{{ end }}
2 Likes

Thanks, this is great!

There is just on thing missing in your code: when you split .Content matching the footnotes opening tag (<section class="footnotes" role="doc-endnotes">), the pattern will not be in the splitted string.

So, for reference, the working solution is:

<!-- store the beginning of the footnotes specific HTML generated by the Markdown processor into a variable -->
{{ $footnotes_tag:= `<section class="footnotes" role="doc-endnotes">` }}

{{ if strings.Contains .Content $footnotes_tag }}

  <!-- split content and store the result into a variable -->
  {{ $split := split .Content $footnotes_tag }}

  <!-- render content before footnotes -->
  {{ index $split 0 | safeHTML }}

  <!--
    Add template logic here!
  -->
  
  <!-- render footnotes -->
  {{ $footnotes_tag | safeHTML }}{{ index $split 1 | safeHTML }}

{{ else }}
  {{ .Content }}
{{ end }}
1 Like

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