Templates in GoloScript
Guide to GoloScript’s template system (Go template syntax).
Introduction
GoloScript uses Go template syntax for dynamic text generation.
Basic Syntax
Simple Substitution
let tmpl = "Hello, {{.Name}}!"
let data = DynamicObject(): define("Name", "Alice")
let result = template(tmpl, data)
# → "Hello, Alice!"
Property Access
let tmpl = """
User: {{.User.Name}}
Email: {{.User.Email}}
"""
let user = DynamicObject()
: define("Name", "Bob")
: define("Email", "bob@example.com")
let data = DynamicObject(): define("User", user)
let result = template(tmpl, data)
Iteration
Range Loop
let tmpl = """
{{range .Items}}- {{.}}
{{end}}
"""
let data = DynamicObject()
: define("Items", list["A", "B", "C"])
let result = template(tmpl, data)
# → - A
# → - B
# → - C
With Index
let tmpl = """
{{range $i, $item := .Items}}{{$i}}: {{$item}}
{{end}}
"""
Conditionals
let tmpl = """
{{if .IsActive}}Status: ACTIVE{{else}}Status: INACTIVE{{end}}
"""
let data = DynamicObject(): define("IsActive", true)
let result = template(tmpl, data)
# → "Status: ACTIVE"
Use Cases
JSON Generation
let jsonTmpl = """
{
"id": {{.ID}},
"name": "{{.Name}}",
"active": {{.Active}}
}
"""
HTML Generation
let htmlTmpl = """
<div class="user">
<h2>{{.Name}}</h2>
<p>{{.Bio}}</p>
</div>
SQL Generation
let sqlTmpl = """
INSERT INTO users (name, email, age)
VALUES ('{{.Name}}', '{{.Email}}', {{.Age}})
"""
Summary
- Syntax: Go templates (
{{.Field}}) - Iteration:
{{range .Items}}...{{end}} - Conditionals:
{{if .Cond}}...{{else}}...{{end}} - Uses: JSON, HTML, SQL, configuration