Skip to content

Repository files navigation

AtomicGo



AtomicGo | f

DownloadsLatest ReleaseTestsCoverageUnit test countLicense: MITGo report


Documentation | Contributing | Code of Conduct


go get atomicgo.dev/f

f

import"atomicgo.dev/f"

Package f is the closest thing to template literals in Go.

F is a simple, fast and safe way to format strings in Go, with a familiar syntax. It evaluates expressions inside `${}` and replaces them with their values.

The expressions support many operators, including ternary operator, and function calls. See the syntax here: https://expr.medv.io/docs/Language-Definition

package main
import (
"fmt""atomicgo.dev/f"
)
typePersonstruct {
NamestringAgeint
}
funcmain() {
// Format a string with a structjohn:=Person{Name: "Bob", Age: 22}
fmt.Println(f.Format("${Name} is ${Age} years old", john))
// Format a string with a mapalice:=map[string]any{"Name": "Alice", "Age": 27}
fmt.Println(f.Format("${Name} is ${Age} years old", alice))
// Evaluate an expressionfmt.Println(f.Format("John is 22 years old: ${Age == 22}", john))
// Ternary operatorfmt.Println(f.Format("John is 22 years old: ${Age == 22 ? 'yes' : 'no'}", john))
}

Output

Bob is 22 years old
Alice is 27 years old
John is 22 years old: true
John is 22 years old: yes

Index

func Format

funcFormat(templatestring, data...any) string

Format formats the template string.

funcFormatSafe(templatestring, data...any) (string, error)

FormatSafe formats the template string and returns an additional, optional error, if something goes wrong.

type Parsed

Parsed contains a parsed template string, ready to be evaluated.

typeParsedstruct {
TemplatestringParts []Part
}

func Parse

funcParse(templatestring) Parsed

Parse parses a template string into a Parsed struct.

func (Parsed) Eval

func (parsedParsed) Eval(dataany) (string, error)

Eval evaluated expressions in the parsed template string.

func (Parsed) String

func (parsedParsed) String() string

String returns the parsed template parts as a single string.

type Part

Part is a single part of a template string. Can either be a raw string, or an expression.

typePartstruct {
ValuestringParsedbool
}

Generated by gomarkdoc


AtomicGo.dev · with ❤️ by @MarvinJWendt | mjw.dev

About

🦄 The closest thing to template literals in Go. Parse expressions in strings - the simple way.

Topics

Resources

Code of conduct

Stars

4 stars

Watchers

1 watching

Forks

Releases

Sponsor this project

Packages

Used by

Contributors

Languages

Generated from atomicgo/template