jsontemplate

package
v0.6.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 12, 2024 License: AGPL-3.0 Imports: 6 Imported by: 0

README

JSON Template

This library is an ugly hack that pretends to be a template/json package that I wish Go had, but doesn't. When you provide it with a text template for a JSON document, this library can generate new documents for each set of value substitutions you provide.

This is a shockingly bad way to make sure that character sequences are escaped properly in the resulting JSON. I wish there were another way, but I gots places to be, and I can't wait around right now for a better solution. So if you have one, I can't wait to replace this with something better.

Example Code
// Define a "text-like" template containing JSON only.
template := New(`{"template": "Hello, {{.name}}!"}`)

// Pass in values and a result to populate
value := map[string]any{"name": "World"}
result := make(map[string]any)

// Execute it like a normal template.  The JSON is unmarshaled into the result.
if err := template.Execute(&result, value); err != nil {
	fmt.Println("Error: ", err)
}

fmt.Println(result["template"]) // Output: Hello, World!
WTF Is Happening?

The short version is that this library wraps the html/template package, and passes your JSON templates through inside of a <script> tag wrapper that it discards before unmarshalling the finished results.

As I alluded to above, I'm disappointed in myself for thinking of this solution, just as I'm disappointed in your for considering using it. Perhaps someone out there will come up with a better way and we can rid ourselves of this nightmare once and for all.

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Option

type Option func(*Template)

func WithStrictMode

func WithStrictMode() Option

WithStrictMode sets the strict mode option for the template, using the standard Go unmarshaller for JSON

type Template

type Template struct {
	// contains filtered or unexported fields
}

func New

func New(input string, options ...Option) (Template, error)

func (*Template) Execute

func (t *Template) Execute(result any, value any) error

Execute uses the parsed template to execute the provided value and populate the result variable.

Example
template, _ := New(`{"template": "Hello, {{.name}}!"}`)

data := map[string]any{"name": "World"}
result := make(map[string]any)

if err := template.Execute(&result, data); err != nil {
	fmt.Println("Error: ", err)
}

fmt.Println(result["template"]) 
Output:

Hello, World!

func (*Template) Funcs

func (t *Template) Funcs(funcMap template.FuncMap)

Funcs adds the functions to the template's function map. It is a pass-through to the underlying template.Funcs method.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL