Documentation
¶
Overview ¶
Package giom is an elegant templating engine for Go Programming Language. It is inspired from HAML and Jade.
Tags ¶
A tag is simply a word:
html
is converted to
<html></html>
It is possible to add ID and CLASS attributes to tags:
div#main span.time
are converted to
<div id="main"></div> <span class="time"></span>
Any arbitrary attribute name / value pair can be added this way:
a[href="http://www.google.com"]
You can mix multiple attributes together
a#someid[href="/"][title="Main Page"].main.link Click Link
gets converted to
<a id="someid" class="main link" href="/" title="Main Page">Click Link</a>
It is also possible to define these attributes within the block of a tag
a #someid [href="/"] [title="Main Page"] .main .link | Click Link
Doctypes ¶
To add a doctype, use `!!!` or `doctype` keywords:
!!! transitional // <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
or use `doctype`
doctype 5 // <!DOCTYPE html>
Available options: `5`, `default`, `xml`, `transitional`, `strict`, `frameset`, `1.1`, `basic`, `mobile`
Tag Content ¶
For single line tag text, you can just append the text after tag name:
p Testing!
would yield
<p>Testing!</p>
For multi line tag text, or nested tags, use indentation:
html head title Page Title body div#content p | This is a long page content | These lines are all part of the parent p a[href="/"] Go To Main Page
Data ¶
Input template data can be reached by key names directly. For example, assuming the template has been executed with following JSON data:
{ "Name": "Ekin", "LastName": "Koc", "Repositories": [ "giom", "dateformat" ], "Avatar": "/images/ekin.jpg", "Friends": 17 }
It is possible to interpolate fields using `${}`
p Welcome ${Name}!
would print
<p>Welcome Ekin!</p>
Attributes can have field names as well
a[title=Name][href="/ekin.koc"]
would print
<a title="Ekin" href="/ekin.koc"></a>
Expressions ¶
giom can expand basic expressions. For example, it is possible to concatenate strings with + operator:
p Welcome ${Name + " " + LastName}
Arithmetic expressions are also supported:
p You need ${50 - Friends} more friends to reach 50!
Expressions can be used within attributes
img[alt=Name + " " + LastName][src=Avatar]
Variables ¶
It is possible to define dynamic variables within templates, all variables must start with a $ character and can be assigned as in the following example:
div $fullname = Name + " " + LastName p Welcome ${$fullname}
If you need to access the supplied data itself (i.e. the object containing Name, LastName etc fields.) you can use `$` variable
p $.Name
Conditions ¶
For conditional blocks, it is possible to use `if <expression>`
div if Friends > 10 p You have more than 10 friends else if Friends > 5 p You have more than 5 friends else p You need more friends
Again, it is possible to use arithmetic and boolean operators
div if Name == "Ekin" && LastName == "Koc" p Hey! I know you..
There is a special syntax for conditional attributes. Only block attributes can have conditions;
div .hasfriends ? Friends > 0
This would yield a div with `hasfriends` class only if the `Friends > 0` condition holds. It is perfectly fine to use the same method for other types of attributes:
div #foo ? Name == "Ekin" [bar=baz] ? len(Repositories) > 0
Iterations ¶
It is possible to iterate over arrays and maps using `each`:
each $repo in Repositories p ${$repo}
would print
p giom p dateformat
It is also possible to iterate over values and indexes at the same time
each $i, $repo in Repositories p .even ? $i % 2 == 0 .odd ? $i % 2 == 1
Includes ¶
A template can include other templates using `include`:
a.giom p this is template a b.giom p this is template b c.giom div include a include b
gets compiled to
div p this is template a p this is template b
Inheritance ¶
A template can inherit other templates. In order to inherit another template, an `extends` keyword should be used. Parent template can define several named blocks and child template can modify the blocks.
master.giom !!! 5 html head block meta meta[name="description"][content="This is a great website"] title block title | Default title body block content subpage.giom extends master block title | Some sub page! block append meta // This will be added after the description meta tag. It is also possible // to prepend something to an existing block meta[name="keywords"][content="foo bar"] block content div#main p Some content here
License (The MIT License)
Copyright (c) 2012 Ekin Koc <ekin@eknkc.com>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Index ¶
- Variables
- func AppendBuiltins(b *gad.Builtins) *gad.Builtins
- func Compile(out io.Writer, input []byte, options Options) (err error)
- func CompileToGad(out io.Writer, input []byte, options Options) (err error)
- type Compiler
- type DirOptions
- type FormatFlag
- type Options
- type Template
- type TemplateBuilder
- func (b *TemplateBuilder) Build() (t *Template, err error)
- func (b *TemplateBuilder) WithBuiltins(builtins *gad.Builtins) *TemplateBuilder
- func (b *TemplateBuilder) WithContext(ctx context.Context) *TemplateBuilder
- func (b *TemplateBuilder) WithModule(module *gad.ModuleInfo) *TemplateBuilder
- func (b *TemplateBuilder) WithModuleMap(moduleMap *gad.ModuleMap) *TemplateBuilder
- type TemplateData
- type TemplateExecutor
- func (e *TemplateExecutor) Args(arg ...gad.Object) *TemplateExecutor
- func (e *TemplateExecutor) Err(out io.Writer) *TemplateExecutor
- func (e *TemplateExecutor) Execute() (vm *gad.VM, result gad.Object, err error)
- func (e *TemplateExecutor) ExecuteModule() (result gad.Object, err error)
- func (e *TemplateExecutor) Global(g ...map[string]any) *TemplateExecutor
- func (e *TemplateExecutor) ManyArgs(args ...gad.Array) *TemplateExecutor
- func (e *TemplateExecutor) NamedArgs(na *gad.NamedArgs) *TemplateExecutor
- func (e *TemplateExecutor) Out(out io.Writer) *TemplateExecutor
- func (e *TemplateExecutor) Template() *Template
- func (e *TemplateExecutor) VmOptsRunner(f func(opts *gad.RunOpts)) *TemplateExecutor
- func (e *TemplateExecutor) VmOptsSetuper(f func(opts *gad.SetupOpts)) *TemplateExecutor
- type ToGadCompiler
Constants ¶
This section is empty.
Variables ¶
var ( BuiltinEscape = &gad.Function{ Name: "escape", Value: func(call gad.Call) (_ gad.Object, err error) { if err = call.Args.CheckLen(1); err != nil { return } var ( value = call.Args.GetOnly(0) s string ) switch t := value.(type) { case gad.RawStr: s = string(t) case gad.Str: s = string(t) default: var v gad.Object if v, err = call.VM.Builtins.Call(gad.BuiltinStr, call); err != nil { return } s = string(v.(gad.Str)) } return gad.RawStr(s), nil }, } AttrFunc = func(vm *gad.VM, name, value gad.Object) (ret gad.RawStr, err error) { var ( toRawStr = vm.Builtins.ArgsInvoker(gad.BuiltinRawStr, gad.Call{VM: vm}) ) if value.IsFalsy() { return } if _, ok := name.(gad.RawStr); !ok { if name, err = toRawStr(name); err != nil { return } } switch t := value.(type) { case gad.Array: var b strings.Builder for _, o := range t { if o.IsFalsy() { continue } if _, ok := o.(gad.RawStr); !ok { if o, err = toRawStr(o); err != nil { return } } b.WriteString(string(o.(gad.RawStr))) b.WriteString(" ") } value = gad.RawStr(strings.TrimSpace(b.String())) case gad.RawStr: case gad.Flag: if t { return gad.RawStr(name.ToString()), nil } return "", nil default: if value, err = toRawStr(value); err != nil { return } } return gad.RawStr(name.ToString() + "=" + strconv.Quote(value.ToString())), nil } BuiltinAttr = &gad.Function{ Name: "attr", Value: func(call gad.Call) (ret gad.Object, err error) { if err = call.Args.CheckLen(2); err != nil { return } ret, err = AttrFunc(call.VM, call.Args.GetOnly(0), call.Args.GetOnly(1)) return }, } BuiltinAttrs = &gad.Function{ Name: "attrs", Value: func(call gad.Call) (_ gad.Object, err error) { var ( b strings.Builder rs gad.RawStr ) call.NamedArgs.Walk(func(na *gad.KeyValue) error { if rs, err = AttrFunc(call.VM, na.K, na.V); err == nil && rs != "" { b.WriteString(" " + string(rs)) } return err }) if err != nil { return } return gad.RawStr(b.String()), nil }, } BuiltinTextWrite = &gad.Function{ Name: "giomTextWrite", Value: func(call gad.Call) (_ gad.Object, err error) { return call.VM.Builtins.Call(gad.BuiltinWrite, call) }, } )
var DefaultDirOptions = DirOptions{".giom", true}
DefaultDirOptions sets expected file extension to ".giom" and recursive search for templates within a directory to true.
var DefaultOptions = Options{PrettyPrint: true}
DefaultOptions sets pretty-printing to true and line numbering to false.
var FuncMap = template.FuncMap{
"__giom_add": runtime_add,
"__giom_sub": runtime_sub,
"__giom_mul": runtime_mul,
"__giom_quo": runtime_quo,
"__giom_rem": runtime_rem,
"__giom_minus": runtime_minus,
"__giom_plus": runtime_plus,
"__giom_eql": runtime_eql,
"__giom_gtr": runtime_gtr,
"__giom_lss": runtime_lss,
"json": runtime_json,
"unescaped": runtime_unescaped,
}
Functions ¶
Types ¶
type Compiler ¶
type Compiler struct { // Compiler options Options // contains filtered or unexported fields }
Compiler is the main interface of giom Template Engine. In order to use an giom template, it is required to create a Compiler and compile an giom source to native Go template.
compiler := giom.New() // Parse the input file err := compiler.ParseFile("./input.giom") if err == nil { // Compile input file to Go template tpl, err := compiler.Compile() if err == nil { // Check built in html/template documentation for further details tpl.Execute(os.Stdout, somedata) } }
func (*Compiler) Compile ¶
Compile compiles giom and writes the Go Template source into given io.Writer instance. You would not be using this unless debugging / checking the output. Please use Compile method to obtain a template instance directly.
func (*Compiler) CompileString ¶
CompileString compiles the template and returns the Go Template source. You would not be using this unless debugging / checking the output. Please use Compile method to obtain a template instance directly.
type DirOptions ¶
type DirOptions struct { // File extension to match for compilation Ext string // Whether or not to walk subdirectories Recursive bool }
DirOptions is used to provide options to directory compilation.
type Options ¶
type Options struct { // Setting if pretty printing is enabled. // Pretty printing ensures that the output html is properly indented and in human readable form. // If disabled, produced HTML is compact. This might be more suitable in production environments. // Default: true PrettyPrint bool // Setting if line number emitting is enabled // In this form, giom emits line number comments in the output template. It is usable in debugging environments. // Default: false LineNumbers bool PreCode string FileName string }
Options defines template output behavior.
type TemplateBuilder ¶
type TemplateBuilder struct {
// contains filtered or unexported fields
}
func NewTemplateBuilder ¶
func NewTemplateBuilder(gadSource []byte) *TemplateBuilder
func (*TemplateBuilder) Build ¶
func (b *TemplateBuilder) Build() (t *Template, err error)
func (*TemplateBuilder) WithBuiltins ¶
func (b *TemplateBuilder) WithBuiltins(builtins *gad.Builtins) *TemplateBuilder
func (*TemplateBuilder) WithContext ¶
func (b *TemplateBuilder) WithContext(ctx context.Context) *TemplateBuilder
func (*TemplateBuilder) WithModule ¶
func (b *TemplateBuilder) WithModule(module *gad.ModuleInfo) *TemplateBuilder
func (*TemplateBuilder) WithModuleMap ¶
func (b *TemplateBuilder) WithModuleMap(moduleMap *gad.ModuleMap) *TemplateBuilder
type TemplateData ¶
type TemplateExecutor ¶
type TemplateExecutor struct {
// contains filtered or unexported fields
}
func NewTemplateExecutor ¶
func NewTemplateExecutor(t *Template) *TemplateExecutor
func (*TemplateExecutor) Args ¶
func (e *TemplateExecutor) Args(arg ...gad.Object) *TemplateExecutor
func (*TemplateExecutor) Err ¶
func (e *TemplateExecutor) Err(out io.Writer) *TemplateExecutor
func (*TemplateExecutor) ExecuteModule ¶
func (e *TemplateExecutor) ExecuteModule() (result gad.Object, err error)
func (*TemplateExecutor) Global ¶
func (e *TemplateExecutor) Global(g ...map[string]any) *TemplateExecutor
func (*TemplateExecutor) ManyArgs ¶
func (e *TemplateExecutor) ManyArgs(args ...gad.Array) *TemplateExecutor
func (*TemplateExecutor) NamedArgs ¶
func (e *TemplateExecutor) NamedArgs(na *gad.NamedArgs) *TemplateExecutor
func (*TemplateExecutor) Out ¶
func (e *TemplateExecutor) Out(out io.Writer) *TemplateExecutor
func (*TemplateExecutor) Template ¶
func (e *TemplateExecutor) Template() *Template
func (*TemplateExecutor) VmOptsRunner ¶
func (e *TemplateExecutor) VmOptsRunner(f func(opts *gad.RunOpts)) *TemplateExecutor
func (*TemplateExecutor) VmOptsSetuper ¶
func (e *TemplateExecutor) VmOptsSetuper(f func(opts *gad.SetupOpts)) *TemplateExecutor
type ToGadCompiler ¶
type ToGadCompiler struct {
// contains filtered or unexported fields
}
func NewToGadCompiler ¶
func NewToGadCompiler(c *Compiler) *ToGadCompiler
func (*ToGadCompiler) Format ¶
func (w *ToGadCompiler) Format(f FormatFlag) *ToGadCompiler
func (*ToGadCompiler) PreCode ¶
func (w *ToGadCompiler) PreCode(s string) *ToGadCompiler