func New
New creates a new Replacer instance with optional initial replacements. It accepts pairs where each pair consists of a placeholder string and its corresponding callback function.
Example:
Package dynreplacer provides a simple template engine for handling dynamic content replacement. It is similar to stri...
gno.land/p/moul/dynreplacer/v1Simple template engine for dynamic content replacement.
Part of moul/gno-contracts — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.
Provenance: imported — see https://github.com/moul/gno-contracts/pull/2 for context and metadata.
⚠️ Disclaimer: provided as-is, without warranty; not security-audited. Full disclaimer: DISCLAIMER.
Package dynreplacer provides a simple template engine for handling dynamic content replacement. It is similar to strings.Replacer but with lazy execution of replacements, making it more optimization-friendly in several cases. While strings.Replacer requires all replacement values to be computed upfront, dynreplacer only executes the callback functions for placeholders that actually exist in the template, avoiding unnecessary computations.
The package ensures efficient, non-recursive replacement of placeholders in a single pass. This lazy evaluation approach is particularly beneficial when: - Some replacement values are expensive to compute - Not all placeholders are guaranteed to be present in the template - Templates are reused with different content
Example usage:
1r := dynreplacer.New(
2 dynreplacer.Pair{":name:", func() string { return "World" }},
3 dynreplacer.Pair{":greeting:", func() string { return "Hello" }},
4)
5result := r.Replace("Hello :name:!") // Returns "Hello World!"
The replacer caches computed values, so subsequent calls with the same placeholder will reuse the cached value instead of executing the callback again:
New creates a new Replacer instance with optional initial replacements. It accepts pairs where each pair consists of a placeholder string and its corresponding callback function.
Example:
Pair represents a placeholder and its callback function
Replacer manages dynamic placeholders, their associated functions, and cached values.
ClearCache clears all cached values, forcing re-computation on next Replace.
RegisterCallback associates a placeholder with a function to generate its content.
Replace processes the given layout, replacing placeholders with cached or newly computed values.