gomponents

package module
v0.11.0 Latest Latest
Warning

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

Go to latest
Published: Nov 16, 2020 License: MIT Imports: 4 Imported by: 0

README

gomponents

GoDoc codecov

gomponents are declarative view components in Go, that can render to HTML5. gomponents aims to make it easy to build HTML5 pages of reusable components, without the use of a template language. Think server-side-rendered React, but without the virtual DOM and diffing.

The implementation is still incomplete, but usable. The API may change until version 1 is reached.

Check out the blog post gomponents: declarative view components in Go for background.

Features

  • Write declarative HTML5 in Go without all the strings, so you get
    • Type safety
    • Auto-completion
    • Nice formatting with gofmt
  • Simple API that's easy to learn and use
  • Build reusable view components
  • No external dependencies

Usage

Get the library using go get:

go get -u github.com/maragudk/gomponents

Then do something like this:

package main

import (
	"net/http"

	g "github.com/maragudk/gomponents"
	"github.com/maragudk/gomponents/attr"
	"github.com/maragudk/gomponents/el"
)

func main() {
	_ = http.ListenAndServe("localhost:8080", handler())
}

func handler() http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		page := Page("Hi!", r.URL.Path)
		_ = page.Render(w)
	}
}

func Page(title, path string) g.Node {
	return el.Document(
		el.HTML(
			g.Attr("lang", "en"),
			el.Head(
				el.Title(title),
				el.Style(g.Attr("type", "text/css"), g.Raw(".is-active{font-weight: bold}")),
			),
			el.Body(
				Navbar(path),
				el.H1(title),
				el.P(g.Textf("Welcome to the page at %v.", path)),
			),
		),
	)
}

func Navbar(path string) g.Node {
	return g.El("nav",
		el.A("/", attr.Classes{"is-active": path == "/"}, g.Text("Home")),
		el.A("/about", attr.Classes{"is-active": path == "/about"}, g.Text("About")),
	)
}

You could also use a page template to simplify your code a bit:

package main

import (
	"net/http"

	g "github.com/maragudk/gomponents"
	"github.com/maragudk/gomponents/attr"
	c "github.com/maragudk/gomponents/components"
	"github.com/maragudk/gomponents/el"
)

func main() {
	_ = http.ListenAndServe("localhost:8080", handler())
}

func handler() http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		page := Page("Hi!", r.URL.Path)
		_ = page.Render(w)
	}
}

func Page(title, path string) g.Node {
	return c.HTML5(c.DocumentProps{
		Title:       title,
		Language:    "en",
		Head:        []g.Node{el.Style(g.Attr("type", "text/css"), g.Raw(".is-active{font-weight: bold}"))},
		Body:        []g.Node{
			Navbar(path),
			el.H1(title),
			el.P(g.Textf("Welcome to the page at %v.", path)),
		},
	})
}

func Navbar(path string) g.Node {
	return g.El("nav",
		el.A("/", attr.Classes{"is-active": path == "/"}, g.Text("Home")),
		el.A("/about", attr.Classes{"is-active": path == "/about"}, g.Text("About")),
	)
}

For more complete examples, see the examples directory.

Documentation

Overview

Package gomponents provides declarative view components in Go, that can render to HTML5. The primary interface is a Node, which has a single function Render, which should render the Node to a string. Furthermore, NodeFunc is a function which implements the Node interface by calling itself on Render. All DOM elements and attributes can be created by using the El and Attr functions. The package also provides a lot of convenience functions for creating elements and attributes with the most commonly used parameters. If they don't suffice, a fallback to El and Attr is always possible.

Index

Constants

View Source
const (
	ElementType = NodeType(iota)
	AttributeType
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Node

type Node interface {
	Render(w io.Writer) error
}

Node is a DOM node that can Render itself to a io.Writer.

func Attr

func Attr(name string, value ...string) Node

Attr creates an attr DOM Node. If one parameter is passed, it's a name-only attribute (like "required"). If two parameters are passed, it's a name-value attribute (like `class="header"`). More parameter counts make Attr panic. Use this if no convenience creator exists.

func Group added in v0.7.0

func Group(children []Node) Node

Group multiple Nodes into one Node. Useful for concatenation of Nodes in variadic functions. The resulting Node cannot Render directly, trying it will panic. Render must happen through a parent element created with El or a helper.

func Map added in v0.11.0

func Map(length int, cb func(i int) Node) []Node

Map something enumerable to a list of Nodes. Example:

items := []string{"hat", "partyhat"}

lis := g.Map(len(items), func(i int) g.Node {
	return g.El("li", g.Text(items[i]))
})

list := g.El("ul", lis...)

type NodeFunc

type NodeFunc func(io.Writer) error

NodeFunc is render function that is also a Node of ElementType.

func El

func El(name string, children ...Node) NodeFunc

El creates an element DOM Node with a name and child Nodes. Use this if no convenience creator exists. See https://dev.w3.org/html5/spec-LC/syntax.html#elements-0 for how elements are rendered. No tags are ever omitted from normal tags, even though it's allowed for elements given at https://dev.w3.org/html5/spec-LC/syntax.html#optional-tags If an element is a void kind, non-attribute nodes are ignored.

func Raw

func Raw(t string) NodeFunc

Raw creates a raw Node that just Renders the unescaped string t.

func Text

func Text(t string) NodeFunc

Text creates a text DOM Node that Renders the escaped string t.

func Textf added in v0.4.0

func Textf(format string, a ...interface{}) NodeFunc

Textf creates a text DOM Node that Renders the interpolated and escaped string t.

func (NodeFunc) Render

func (n NodeFunc) Render(w io.Writer) error

func (NodeFunc) String added in v0.2.0

func (n NodeFunc) String() string

String satisfies fmt.Stringer.

func (NodeFunc) Type added in v0.11.0

func (n NodeFunc) Type() NodeType

type NodeType added in v0.11.0

type NodeType int

NodeType describes what type of Node it is, currently either an element or an attribute. Nodes default to being ElementType.

Directories

Path Synopsis
Package assert provides testing helpers.
Package assert provides testing helpers.
Package attr provides shortcuts and helpers to common HTML attributes.
Package attr provides shortcuts and helpers to common HTML attributes.
Package components provides high-level components that are composed of low-level elements and attributes.
Package components provides high-level components that are composed of low-level elements and attributes.
Package el provides shortcuts and helpers to common HTML elements.
Package el provides shortcuts and helpers to common HTML elements.
examples

Jump to

Keyboard shortcuts

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