simpl

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Apr 10, 2026 License: MIT Imports: 3 Imported by: 0

README

simpl

A lightweight HTML templating library for Go. Build pages by composing plain Go structs and constructor functions. No separate template files, no DSL, no parsing step.

Install

go get github.com/hoakus/simpl

Quick start

package main

import (
    "os"

    "github.com/hoakus/simpl"
    "github.com/hoakus/simpl/elements"
)

func main() {
    page := elements.PageTemplate(
        "Hello, Website!",
        "Baby's first website",
        "/static/style.css",
        "/static/main.js",
        elements.H1("Welcome!"),
        elements.Main(nil,
            elements.Div(simpl.Attrs(
                simpl.Attr(simpl.Class, "container"),
            )),
            elements.Text("This is my container."),
        ),
    )

    _ = page.Render(os.Stdout)
}

Building elements by hand

The simpl package exposes the core types so you can construct elements directly:

btn := simpl.Element{
    Tag: simpl.Button,
    Attrs: simpl.Attrs(
        simpl.Attr(simpl.Class, "primary"),
        simpl.Attr(simpl.Type, "submit"),
    ),
    Content: "Save",
}
_ = btn.Render(os.Stdout)
// <button class="primary" type="submit">Save</button>

The elements package wraps the same construction in helper functions like Div, H1, Img, and so on, so you don't need to write the struct literal at every node.

API at a glance

  • simpl.Element — the building block. Fields: Tag, Attrs, Children, Content. An empty Tag becomes a raw text node (escaped content only).
  • simpl.Attr(key, value) / simpl.Attrs(...) — build attributes. A boolean attribute (e.g. disabled) is created with an empty value.
  • Element.Render(io.Writer) error — writes the element and its subtree as HTML. When the root tag is <html>, <!DOCTYPE html> is emitted first.
  • Text and attribute values are HTML-escaped via html.EscapeString.
  • HTML5 void elements (br, img, meta, link, input, …) render without a closing tag.

Custom attributes and tags

The constants in enums.go cover common HTML keys and tags. For anything else (data-*, custom elements, future spec additions), use the converters:

simpl.Attr(simpl.ToAttr("data-user-id"), "42")
simpl.Element{Tag: simpl.ToTag("my-widget")}

Templates

The elements package includes a few opinionated helpers for common page elements:

  • PageTemplate(title, desc, stylesheet, script, body...) — full HTML document with charset, viewport, title, description meta, and one stylesheet/script link.
  • HeaderTemplate(logo, nav, actions...)<header> with site-header / header-container / header-logo / header-nav / header-actions classes.
  • FooterTemplate(bottom, columns...)<footer> with site-footer / footer-grid / footer-bottom classes.
  • UlTemplate(class, items...) / OlTemplate(class, items...) — wraps each provided element in an <li>.

License

MIT — see LICENSE.

Documentation

Overview

Package simpl is a lightweight html templating system

Use go structs to create html elements

Index

Constants

View Source
const (
	Description = "description" // value for <meta name="description">
	Viewport    = "viewport"    // value for <meta name="viewport">
	Stylesheet  = "stylesheet"  // value for <link rel="stylesheet">
)

Common attribute values that pair with specific keys (e.g., the value for <meta name="description">). These are plain strings, not AttrType, because they appear on the right-hand side of an attribute, not as the key.

Variables

This section is empty.

Functions

This section is empty.

Types

type AttrType

type AttrType string

AttrType is the attribute key attached to an HTML element, followed by a value

const (
	// ---- Global attributes (valid on most/all elements) ----
	Class           AttrType = "class"           // class the element belongs to | CSS operator = '.'
	ID              AttrType = "id"              // unique identifier of the element | CSS operator = '#'
	StyleAttr       AttrType = "style"           // inline CSS style for the element
	TitleAttr       AttrType = "title"           // advisory information (tooltip text)
	Lang            AttrType = "lang"            // language of the element's content
	Dir             AttrType = "dir"             // text direction (ltr, rtl, auto)
	Hidden          AttrType = "hidden"          // hides the element from rendering
	TabIndex        AttrType = "tabindex"        // tab order of the element
	Role            AttrType = "role"            // ARIA role of the element
	Draggable       AttrType = "draggable"       // whether the element is draggable
	ContentEditable AttrType = "contenteditable" // whether the element's content is editable
	Spellcheck      AttrType = "spellcheck"      // whether spellcheck is enabled
	Translate       AttrType = "translate"       // whether the element should be translated
	AccessKey       AttrType = "accesskey"       // keyboard shortcut to focus/activate the element

	// ---- Anchor / link target ----
	HypertextReference AttrType = "href"           // URL of the page the link goes to
	Target             AttrType = "target"         // target of where to open the link or submit the form
	Relationship       AttrType = "rel"            // relationship between current and linked document
	Download           AttrType = "download"       // tells the browser to download the linked resource
	HrefLang           AttrType = "hreflang"       // language of the linked document
	ReferrerPolicy     AttrType = "referrerpolicy" // referrer info to send when fetching the resource

	// ---- Image / media ----
	SourceAttr      AttrType = "src"         // location (URL) of external source
	AlternativeText AttrType = "alt"         // alternate text when the original element fails to display
	Width           AttrType = "width"       // width of the element
	Height          AttrType = "height"      // height of the element
	SrcSet          AttrType = "srcset"      // list of image sources for different screen sizes
	Sizes           AttrType = "sizes"       // image sizes for different page layouts
	Loading         AttrType = "loading"     // lazy/eager loading hint
	Decoding        AttrType = "decoding"    // image decoding hint
	CrossOrigin     AttrType = "crossorigin" // CORS settings for the resource

	// ---- Form ----
	Action       AttrType = "action"       // URL to submit the form to
	Method       AttrType = "method"       // HTTP method to use when submitting (GET/POST)
	EncType      AttrType = "enctype"      // encoding type used when submitting form data
	AutoComplete AttrType = "autocomplete" // whether the form/input should autocomplete
	NoValidate   AttrType = "novalidate"   // skip form validation on submit
	Name         AttrType = "name"         // name of the element (for form submission and meta)
	Value        AttrType = "value"        // value of the element

	// ---- Input ----
	Type        AttrType = "type"        // type of the input/button/script/link
	Placeholder AttrType = "placeholder" // placeholder text for an input
	Required    AttrType = "required"    // marks the input as required
	Disabled    AttrType = "disabled"    // marks the input/button as disabled
	ReadOnly    AttrType = "readonly"    // marks the input as read-only
	Min         AttrType = "min"         // minimum value
	Max         AttrType = "max"         // maximum value
	Pattern     AttrType = "pattern"     // regex pattern the value must match
	MaxLength   AttrType = "maxlength"   // maximum length of the value
	MinLength   AttrType = "minlength"   // minimum length of the value
	Multiple    AttrType = "multiple"    // allow multiple values
	Step        AttrType = "step"        // legal number intervals for an input
	Checked     AttrType = "checked"     // pre-selects a checkbox/radio
	Accept      AttrType = "accept"      // file types accepted by a file input
	For         AttrType = "for"         // associates a label with an input element

	// ---- Semantic ----
	DateTime AttrType = "datetime" // machine-readable date/time for <time>
	Open     AttrType = "open"     // whether a <details> element is expanded
	Cite     AttrType = "cite"     // URL of the source for a <blockquote>

	// ---- Meta ----
	CharacterSet AttrType = "charset"    // specifies character encoding for the HTML document
	Content      AttrType = "content"    // content value for a meta tag
	HTTPEquiv    AttrType = "http-equiv" // pragma directive for a meta tag

	// ---- Link / script ----
	Integrity AttrType = "integrity" // subresource integrity hash
	Async     AttrType = "async"     // load script asynchronously
	Defer     AttrType = "defer"     // defer script execution until parse complete
	NoModule  AttrType = "nomodule"  // do not run on browsers that support ES modules
	Media     AttrType = "media"     // media query for the linked resource
	As        AttrType = "as"        // type of resource being preloaded

	// ---- Table ----
	ColSpan          AttrType = "colspan" // number of columns a cell should span
	RowSpan          AttrType = "rowspan" // number of rows a cell should span
	TableHeadersAttr AttrType = "headers" // header cells associated with this cell
	TableScope       AttrType = "scope"   // whether a header cell is for a row, column, etc

	// ---- Audio / video ----
	Controls AttrType = "controls" // show playback controls
	AutoPlay AttrType = "autoplay" // begin playback automatically
	Loop     AttrType = "loop"     // restart playback when finished
	Muted    AttrType = "muted"    // start muted
	Preload  AttrType = "preload"  // preload hint
	Poster   AttrType = "poster"   // poster image for a video before it plays

	// ---- Common ARIA (escape hatch: AttrType("aria-foo") for the rest) ----
	AriaLabel       AttrType = "aria-label"
	AriaHidden      AttrType = "aria-hidden"
	AriaDescribedBy AttrType = "aria-describedby"
	AriaLabelledBy  AttrType = "aria-labelledby"
)

AttrType constants

func ToAttr

func ToAttr(s string) AttrType

ToAttr type converts the given string into a simpl.AttrType

type Attribute

type Attribute struct {
	Key   AttrType
	Value string
}

Attribute is an HTML tag attribute defined as a go struct

Key is the attribute name (e.g. "class", "id"). Value is the attribute value. An empty Value renders as a boolean attribute (e.g. "disabled").

func Attr

func Attr(key AttrType, value string) Attribute

Attr constructs a single Attribute from a key and value.

The enum constants in this package (Class, ID, Source, …) are intended for use as the key. For data-* / aria-* / custom keys, wrap the string with ToAttr (e.g. simpl.Attr(simpl.ToAttr("data-foo"), "bar")).

func Attrs

func Attrs(attrs ...Attribute) []Attribute

Attrs gathers a variadic list of Attribute into a slice. It exists so element constructors can be called without writing []simpl.Attribute{...} at every call site.

type Element

type Element struct {
	Tag      Tag
	Attrs    []Attribute
	Children []Element
	Content  string
}

Element is an HTML element defined as a go struct

Tag = h1, p, div, and so on. An empty Tag is treated as a raw text node: only the (escaped) Content is written, with no surrounding tag. Attrs = class, id, etc. Children = nested Elements Content = text content rendered before children (HTML-escaped)

func (Element) Render

func (e Element) Render(w io.Writer) error

Render writes the element (and its subtree) to writer as HTML.

type Tag

type Tag string

Tag is the start/end tag of an HTML element, defining what that element is and does

const (
	// Standard Tags
	HTML            Tag = "html"       // declares the following text/data as HTML elements
	Head            Tag = "head"       // contains meta-data about the HTML document
	Body            Tag = "body"       // contains the content of all elements following the Head elem
	Header          Tag = "header"     // pre-defined header container
	Main            Tag = "main"       // the main content of the document
	Footer          Tag = "footer"     // pre-defined footer container
	Division        Tag = "div"        // a block container for HTML elements
	Section         Tag = "section"    // defines a section of the document
	Article         Tag = "article"    // defines an independent, self-contained article
	Aside           Tag = "aside"      // defines content aside from the page content
	Nav             Tag = "nav"        // defines navigation links
	H1              Tag = "h1"         // header Text - Size 1 (one per page)
	H2              Tag = "h2"         // header Text - Size 2
	H3              Tag = "h3"         // header Text - Size 3
	H4              Tag = "h4"         // header Text - Size 4
	H5              Tag = "h5"         // header Text - Size 5
	H6              Tag = "h6"         // header Text - Size 6
	Paragraph       Tag = "p"          // defines a paragraph. Browsers surround with blank lines
	Span            Tag = "span"       // an inline container for HTML elements
	OrderedList     Tag = "ol"         // an ordered list of items (<li>)
	UnorderedList   Tag = "ul"         // an unordered (bulleted) list of items (<li>)
	ListItem        Tag = "li"         // a list item, to be used within lists (<ol> && <ul>)
	Anchor          Tag = "a"          // defines a hyperlink to link from one page to another
	Image           Tag = "img"        // used to embed an image (via href) within the page
	Input           Tag = "input"      // specifies an input field where the user can enter data
	Form            Tag = "form"       // used to create an HTML form element for user input
	Button          Tag = "button"     // defines an interactable HTML button element
	Label           Tag = "label"      // defines a label for an <input> element
	Select          Tag = "select"     // defines a drop-down list
	Option          Tag = "option"     // defines an option in a drop-down list
	Textarea        Tag = "textarea"   // defines a multi-line text input control
	Table           Tag = "table"      // defines a table
	TableHeader     Tag = "thead"      // groups the header content in a table
	TableBody       Tag = "tbody"      // groups the body content in a table
	TableFooter     Tag = "tfoot"      // groups the footer content in a table
	TableRow        Tag = "tr"         // defines a row in a table
	TableHeaderCell Tag = "th"         // defines a header cell in a table
	TableDataCell   Tag = "td"         // defines a standard cell in a table
	Fieldset        Tag = "fieldset"   // groups related form elements with a border
	Legend          Tag = "legend"     // defines a caption for a <fieldset>
	Strong          Tag = "strong"     // defines important text (typically bold)
	Emphasis        Tag = "em"         // defines emphasized text (typically italic)
	Blockquote      Tag = "blockquote" // defines a section quoted from another source
	Code            Tag = "code"       // defines inline code
	Preformatted    Tag = "pre"        // defines preformatted text (preserves whitespace)
	Details         Tag = "details"    // defines a disclosure widget the user can open/close
	Summary         Tag = "summary"    // defines the visible heading for a <details> element
	Small           Tag = "small"      // defines smaller text (fine print, disclaimers)
	Time            Tag = "time"       // defines a date/time value

	// Meta (head only) tags
	Meta   Tag = "meta"   // defines metadata about an HTML document
	Title  Tag = "title"  // defines the title of an HTML document - used by browser tabs
	Link   Tag = "link"   // defines relationship between current document and ext. resource
	Script Tag = "script" // used to embed client-side scripting (JavaScript)
	Style  Tag = "style"  // defines style information (CSS) for a document

	// Self-closing (void) tags
	Area           Tag = "area"   // defines an area inside an image map
	Base           Tag = "base"   // specifies the base URL for all relative URLs in the document
	Break          Tag = "br"     // inserts a single line break
	Col            Tag = "col"    // specifies column properties for a <colgroup>
	Embed          Tag = "embed"  // defines a container for an external resource
	HorizontalRule Tag = "hr"     // defines a thematic break in an HTML document
	Source         Tag = "source" // defines multiple media resources for media elements
	Track          Tag = "track"  // defines text tracks for media elements
	Wbr            Tag = "wbr"    // defines a possible line-break opportunity
)

Tag constants

func ToTag

func ToTag(s string) Tag

ToTag type converts the given string into a simpl.Tag

Directories

Path Synopsis
Package elements is a package for standard html elements using simpl
Package elements is a package for standard html elements using simpl

Jump to

Keyboard shortcuts

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