-
-
Notifications
You must be signed in to change notification settings - Fork 397
Declarative Syntax
Writing components requires to describe how the UI looks like.
In the previous version of this package, this was done by writing HTML code as templated strings where Go code was called by hidden mechanisms.
While it was working well, it had some drawback related to HTML written in Go strings:
- No linter
- No code format
- No code editor auto-complete
The result was that it was easy to make mistakes when writing HTML.
The app package now provides interfaces and functions based on HTML elements. By using a chaining mechanism and the Go syntax, writing a UI is now done in a declarative fashion, without using another language.
Here is an example that describes a title and its text:
ui := app.Div().Body(
app.H1().
Class("title").
Body(
app.Text("Build a GUI with Go"),
),
app.P().
Class("text").
Body(
app.Text("Just because Go and this package are really awesome!"),
),
)The app package provides an interface for each standard HTML element.
Here is a simplified version of the interface for a <div>:
type HTMLDiv interface {
// Attributes:
Body(nodes ...Node) HTMLDiv
Class(v string) HTMLDiv
ID(v string) HTMLDiv
Style(k, v string) HTMLDiv
// Event handlers:
OnClick(h EventHandler) HTMLDiv
OnKeyPress(h EventHandler) HTMLDiv
OnMouseOver(h EventHandler) HTMLDiv
}An HTML element can be created by calling a function named after its name:
div := app.Div()Element interfaces provide methods to set its attributes:
div := app.Div().Class("my-class")Multiple attributes can be set by using the chaining mechanism:
div := app.Div().
ID("id-name").
Class("class-name")Style is an attribute that sets the element style with CSS. It is set by calling the Style() method with a CSS property name and value.
div := app.Div().Style("width", "400px")Multiple styles can be set by calling the Style() method successively:
div := app.Div().
Style("width", "400px").
Style("height", "200px").
Style("background-color", "deepskyblue")Event handlers are functions that are called when an HTML event occurs. They must have the following signature:
func(src app.Value, e app.Event)Like attributes, element interfaces provide methods to attach event handlers the events it generates:
onClick := func(src app.Value, e app.Event) {
fmt.Println("onClick is called")
}
div := app.Div().OnClick(onClick)Note that app.Value and app.Event are JavaScript objects wrapped in Go interfaces. See the JS Values topic to know more about it.