[SOLVED] How can I improve this string replace code?

I have this code in my Hugo theme:

<!-- Fetch last heading in text -->
{{ $headings := findRE `<h[2-4].+>.+</h[2-4]+>` $cnt }}
{{ $lastHeading := index $headings (sub (len $headings) 1) }}
<!-- Add banner to last heading -->
{{ $cnt = replace $cnt $lastHeading (print $banner $lastHeading) }}	

What happens here is that I first find all headings in the text:

{{ $headings := findRE `<h[2-4].+>.+</h[2-4]+>` $cnt }}

Then I fetch the last found heading:

{{ $lastHeading := index $headings (sub (len $headings) 1) }}

And then I update my earlier-made $cnt variable with replace. That way I replace the last heading with my $banner text variable + the last heading:

{{ $cnt = replace $cnt $lastHeading (print $banner $lastHeading) }}

My question

  • Is there a better way to code the above situation?

Why I ask:
The above Hugo template code works for me. But I run into memory issues; hugo.exe takes around 2GB and later runs out of computer memory.

I located that error cause in updating the existing variable. This doesn’t give me memory issues:

{{ replace $cnt $lastHeading (print $banner $lastHeading) }}

But as soon as I update the earlier-made variable problems begin:

{{ $cnt = replace $cnt $lastHeading (print $banner $lastHeading) }}

But I have to update $cnt because later on in the same partial I do additional replacements (like inserting the TOC).

And so I’m looking for more efficient Hugo template code that does the same thing. Can you help? :slight_smile:


Hugo Static Site Generator v0.51/extended windows/amd64 BuildDate: unknown
GOOS="windows"
GOARCH="amd64"
GOVERSION="go1.11"

I fixed the above problem when I realised that the memory issue happened with empty draft files, which were also processed by my template code. Once I made Hugo only perform string replacement on non-draft files, the memory issue went away and I could use the above template code.