valyala / quicktemplate

Fast, powerful, yet easy to use template engine for Go. Optimized for speed, zero memory allocations in hot paths. Up to 20x faster than html/template

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

[Question] Inject content after template render

nd2s opened this issue · comments

Currently I am embedding SVG icons by calling a function {%= p.SVGSymbol("svg/icon/close.svg") %} that creates a SVG <use xlink> tag and remembers the symbol being used. And at the end of the template I embed the automatically generated SVG definitions (so that only icons that are actually used are embedded).

I know need to insert the sprite at the beginning of the content - before I know what icons I need to embed.

What would be the best way to achieve that without having to render all templates twice for every call?

Just split the original template func into two template funcs:

  1. The first one - p.PageContents - calls p.SVGSymbol, which remembers the content required for the embedded SVG inside p.
  2. The second one - p.SVGDefinitions - generates SVG definitions for the remembered SVG symbols from the first template.

Then the code would look like:

pageContents := p.PageContents()
svgDefinitions := p.SVGDefinitions()
resultingText := svgDefinitions + pageContents

This code isn't optimal from memory allocations point of view, but it calls p.PageContents only once.