elem

package module
v0.26.0 Latest Latest
Warning

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

Go to latest
Published: Jun 9, 2024 License: MIT Imports: 4 Imported by: 8

README

elem-go logo

elem is a lightweight Go library for creating HTML elements programmatically. Utilizing the strong typing features of Go, elem ensures type safety in defining and manipulating HTML elements, minimizing potential runtime errors. It simplifies the generation of HTML views by providing a simple and intuitive way to create elements and set their attributes, properties, and content.

Features

  • Easily create HTML elements with Go code.
  • Type-safe definition and manipulation of elements, attributes, and properties.
  • Supports common HTML elements and attributes.
  • Utilities for simplified element generation and manipulation.
  • Advanced CSS styling capabilities with the styles subpackage.
  • Use the StyleManager for advanced CSS features like pseudo-classes, animations, and media queries.

Installation

To install elem, use go get:

go get github.com/chasefleming/elem-go

Usage

Import the elem package in your Go code:

import (
    "github.com/chasefleming/elem-go"
    "github.com/chasefleming/elem-go/attrs"
    "github.com/chasefleming/elem-go/styles"
)

Creating Elements

Here's an example of creating a <div> element with nested <h1>, <h2>, and <p> elements using elem:

content := elem.Div(attrs.Props{
    attrs.ID:    "container",
    attrs.Class: "my-class",
},
    elem.H1(nil, elem.Text("Hello, Elem!")),
    elem.H2(nil, elem.Text("Subheading")),
    elem.P(nil, elem.Text("This is a paragraph.")),
)

When the above Go code is executed and the .Render() method is called, it produces the following HTML:

<div id="container" class="my-class">
    <h1>Hello, Elem!</h1>
    <h2>Subheading</h2>
    <p>This is a paragraph.</p>
</div>

Attributes and Styles

The attrs subpackage provides type-safe attribute functions that ensure you're setting valid attributes for your elements. This helps eliminate potential issues at runtime due to misspelled or unsupported attribute names.

For boolean attributes like checked and selected, you can simply assign them the value "true" or "false". When set to "true", the library will correctly render these attributes without needing an explicit value. For instance:

// Using boolean attributes
checkbox := elem.Input(attrs.Props{
    attrs.Type:    "checkbox",
    attrs.Checked: "true",  // This will render as <input type="checkbox" checked>
})

For setting styles, the styles subpackage enables you to create style objects and convert them to inline CSS strings:

// Define a style
buttonStyle := styles.Props{
    styles.BackgroundColor: "blue",
    styles.Color:           "white",
}

// Convert style to inline CSS and apply it
button := elem.Button(
    attrs.Props{
        attrs.Style: buttonStyle.ToInline(),
    },
    elem.Text("Click Me"),
)

See the complete list of supported attributes in the attrs package, and for a full overview of style properties and information on using the styles subpackage, see the styles README.

Rendering Elements

The .Render() method is used to convert the structured Go elements into HTML strings. This method is essential for generating the final HTML output that can be served to a web browser or integrated into templates.

html := content.Render()

In this example, content refers to an elem element structure. When the .Render() method is called on content, it generates the HTML representation of the constructed elements.

NOTE: When using an element, this method automatically includes a preamble in the rendered HTML, ensuring compliance with modern web standards.

Custom Rendering Options

For more control over the rendering process, such as disabling the HTML preamble, use the RenderWithOptions method. This method accepts a RenderOptions struct, allowing you to specify various rendering preferences.

options := RenderOptions{DisableHtmlPreamble: true}
htmlString := myHtmlElement.RenderWithOptions(options)

This flexibility is particularly useful in scenarios where default rendering behaviors need to be overridden or customized.

Generating Lists of Elements with TransformEach

With elem, you can easily generate lists of elements from slices of data using the TransformEach function. This function abstracts the repetitive task of iterating over a slice and transforming its items into elements.

items := []string{"Item 1", "Item 2", "Item 3"}

liElements := elem.TransformEach(items, func(item string) elem.Node {
    return elem.Li(nil, elem.Text(item))
})

ulElement := elem.Ul(nil, liElements)

In this example, we transformed a slice of strings into a list of li elements and then wrapped them in a ul element.

Conditional Rendering with If

elem provides a utility function If for conditional rendering of elements.

isAdmin := true
adminLink := elem.A(attrs.Props{attrs.Href: "/admin"}, elem.Text("Admin Panel"))
guestLink := elem.A(attrs.Props{attrs.Href: "/login"}, elem.Text("Login"))

content := elem.Div(nil,
    elem.H1(nil, elem.Text("Dashboard")),
    elem.If(isAdmin, adminLink, guestLink),
)

In this example, if isAdmin is true, the Admin Panel link is rendered. Otherwise, the Login link is rendered.

None in Conditional Rendering

elem provides a specialized node None that implements the Node interface but does not produce any visible output. It's particularly useful in scenarios where rendering nothing for a specific condition is required.

showWelcomeMessage := false
welcomeMessage := elem.Div(nil, elem.Text("Welcome to our website!"))

content := elem.Div(nil,
    elem.If[elem.Node](showWelcomeMessage, welcomeMessage, elem.None()),
)

In this example, welcomeMessage is rendered only if showWelcomeMessage is true. If it's false, None is rendered instead, which produces no visible output.

Additionally, None can be used to create an empty element, as in elem.Div(nil, elem.None()), which results in <div></div>. This can be handy for creating placeholders or structuring your HTML document without adding additional content.

Supported Elements

elem provides utility functions for creating HTML elements:

  • Document Structure: Html, Head, Body, Title, Link, Meta, Style, Base
  • Text Content: H1, H2, H3, H4, H5, H6, P, Blockquote, Pre, Code, I, Br, Hr, Small, Q, Cite, Abbr, Data, Time, Var, Samp, Kbd
  • Sectioning & Semantic Layout: Article, Aside, FigCaption, Figure, Footer, Header, Hgroup, Main, Mark, Nav, Section
  • Form Elements: Form, Input, Textarea, Button, Select, Optgroup, Option, Label, Fieldset, Legend, Datalist, Meter, Output, Progress
  • Interactive Elements: Details, Dialog, Menu, Summary
  • Grouping Content: Div, Span, Li, Ul, Ol, Dl, Dt, Dd
  • Tables: Table, Tr, Td, Th, TBody, THead, TFoot
  • Hyperlinks and Multimedia: Img, Map, Area
  • Embedded Content: Audio, Iframe, Source, Video
  • Script-supporting Elements: Script, Noscript
  • Inline Semantic: A, Strong, Em, Code, I, B, U, Sub, Sup, Ruby, Rt, Rp

Raw HTML Insertion

The Raw function allows for the direct inclusion of raw HTML content within your document structure. This function can be used to insert HTML strings, which will be rendered as part of the final HTML output.

rawHTML := `<div class="custom-html"><p>Custom HTML content</p></div>`
content := elem.Div(nil,
    elem.H1(nil, elem.Text("Welcome to Elem-Go")),
    elem.Raw(rawHTML), // Inserting the raw HTML
    elem.P(nil, elem.Text("More content here...")), 
)

htmlOutput := content.Render()
// Output: <div><h1>Welcome to Elem-Go</h1><div class="custom-html"><p>Custom HTML content</p></div><p>More content here...</p></div>

NOTE: If you are passing HTML from an untrusted source, make sure to sanitize it to prevent potential security risks such as Cross-Site Scripting (XSS) attacks.

HTML Comments

Apart from standard elements, elem-go also allows you to insert HTML comments using the Comment function:

comment := elem.Comment("Section: Main Content Start")
// Generates: <!-- Section: Main Content Start -->

Advanced CSS Styling with StyleManager

For projects requiring advanced CSS styling capabilities, including support for animations, pseudo-classes, and responsive design via media queries, the stylemanager subpackage offers a powerful solution. Integrated seamlessly with elem-go, it allows developers to programmatically create and manage complex CSS styles within the type-safe environment of Go.

Explore the stylemanager subpackage to leverage advanced styling features in your web applications.

HTMX Integration

We provide a subpackage for htmx integration. Read more about htmx integration here.

Examples

For hands-on examples showcasing the usage of elem, you can find sample implementations in the examples/ folder of the repository. Dive into the examples to get a deeper understanding of how to leverage the library in various scenarios.

Check out the examples here.

Tutorials & Guides

Dive deeper into the capabilities of elem and learn best practices through our collection of tutorials and guides:

Stay tuned for more tutorials and guides in the future!

Contributing

Contributions are welcome! If you have ideas for improvements or new features, please open an issue or submit a pull request.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func If added in v0.6.0

func If[T any](condition bool, ifTrue, ifFalse T) T

If conditionally renders one of the provided elements based on the condition

Types

type CSSGenerator added in v0.25.0

type CSSGenerator interface {
	GenerateCSS() string // TODO: Change to CSS()
}

type CommentNode added in v0.13.0

type CommentNode string

func Comment added in v0.13.0

func Comment(comment string) CommentNode

Comment creates a CommentNode.

func (CommentNode) Render added in v0.13.0

func (c CommentNode) Render() string

func (CommentNode) RenderTo added in v0.13.0

func (c CommentNode) RenderTo(builder *strings.Builder, opts RenderOptions)

func (CommentNode) RenderWithOptions added in v0.17.0

func (c CommentNode) RenderWithOptions(opts RenderOptions) string

type Element

type Element struct {
	Tag      string
	Attrs    attrs.Props
	Children []Node
}

func A

func A(attrs attrs.Props, children ...Node) *Element

A creates an <a> element.

func Abbr added in v0.21.0

func Abbr(attrs attrs.Props, children ...Node) *Element

Abbr creates an <abbr> element.

func Address added in v0.10.0

func Address(attrs attrs.Props, children ...Node) *Element

Address creates an <address> element.

func Area added in v0.18.0

func Area(attrs attrs.Props) *Element

Area creates an <area> element.

func Article added in v0.7.0

func Article(attrs attrs.Props, children ...Node) *Element

Article creates an <article> element.

func Aside added in v0.7.0

func Aside(attrs attrs.Props, children ...Node) *Element

Aside creates an <aside> element.

func Audio added in v0.13.0

func Audio(attrs attrs.Props, children ...Node) *Element

Audio creates an <audio> element.

func B added in v0.21.0

func B(attrs attrs.Props, children ...Node) *Element

B creates a <b> element.

func Base added in v0.22.0

func Base(attrs attrs.Props) *Element

Base creates a <base> element.

func Blockquote added in v0.2.0

func Blockquote(attrs attrs.Props, children ...Node) *Element

Blockquote creates a <blockquote> element.

func Body

func Body(attrs attrs.Props, children ...Node) *Element

Body creates a <body> element.

func Br added in v0.2.0

func Br(attrs attrs.Props) *Element

Br creates a <br> element.

func Button

func Button(attrs attrs.Props, children ...Node) *Element

Button creates a <button> element.

func Cite added in v0.21.0

func Cite(attrs attrs.Props, children ...Node) *Element

Cite creates a <cite> element.

func Code added in v0.2.0

func Code(attrs attrs.Props, children ...Node) *Element

Code creates a <code> element.

func Data added in v0.21.0

func Data(attrs attrs.Props, children ...Node) *Element

Data creates a <data> element.

func Datalist added in v0.10.0

func Datalist(attrs attrs.Props, children ...Node) *Element

Datalist creates a <datalist> element.

func Dd added in v0.7.0

func Dd(attrs attrs.Props, children ...Node) *Element

Dd creates a <dd> element.

func Details added in v0.10.0

func Details(attrs attrs.Props, children ...Node) *Element

Details creates a <details> element.

func Dialog added in v0.10.0

func Dialog(attrs attrs.Props, children ...Node) *Element

Dialog creates a <dialog> element.

func Div

func Div(attrs attrs.Props, children ...Node) *Element

Div creates a <div> element.

func Dl added in v0.7.0

func Dl(attrs attrs.Props, children ...Node) *Element

Dl creates a <dl> element.

func Dt added in v0.7.0

func Dt(attrs attrs.Props, children ...Node) *Element

Dt creates a <dt> element.

func Em added in v0.2.0

func Em(attrs attrs.Props, children ...Node) *Element

Em creates an <em> element.

func Fieldset added in v0.10.0

func Fieldset(attrs attrs.Props, children ...Node) *Element

Fieldset creates a <fieldset> element.

func FigCaption added in v0.10.0

func FigCaption(attrs attrs.Props, children ...Node) *Element

FigCaption creates a <figcaption> element.

func Figure added in v0.10.0

func Figure(attrs attrs.Props, children ...Node) *Element

Figure creates a <figure> element.

func Footer(attrs attrs.Props, children ...Node) *Element

Footer creates a <footer> element.

func Form added in v0.3.0

func Form(attrs attrs.Props, children ...Node) *Element

Form creates a <form> element.

func H1

func H1(attrs attrs.Props, children ...Node) *Element

H1 creates an <h1> element.

func H2

func H2(attrs attrs.Props, children ...Node) *Element

H2 creates an <h2> element.

func H3

func H3(attrs attrs.Props, children ...Node) *Element

H3 creates an <h3> element.

func H4 added in v0.19.0

func H4(attrs attrs.Props, children ...Node) *Element

H4 creates an <h4> element.

func H5 added in v0.19.0

func H5(attrs attrs.Props, children ...Node) *Element

H5 creates an <h5> element.

func H6 added in v0.19.0

func H6(attrs attrs.Props, children ...Node) *Element

H6 creates an <h6> element.

func Head(attrs attrs.Props, children ...Node) *Element

Head creates a <head> element.

func Header(attrs attrs.Props, children ...Node) *Element

Header creates a <header> element.

func Hgroup added in v0.19.0

func Hgroup(attrs attrs.Props, children ...Node) *Element

Hgroup creates an <hgroup> element.

func Hr added in v0.2.0

func Hr(attrs attrs.Props) *Element

Hr creates an <hr> element.

func Html

func Html(attrs attrs.Props, children ...Node) *Element

Html creates an <html> element.

func I added in v0.8.0

func I(attrs attrs.Props, children ...Node) *Element

I creates an <i> element.

func IFrame added in v0.13.0

func IFrame(attrs attrs.Props, children ...Node) *Element

IFrames creates an <iframe> element.

func Img

func Img(attrs attrs.Props) *Element

Img creates an <img> element.

func Input added in v0.3.0

func Input(attrs attrs.Props) *Element

Input creates an <input> element.

func Kbd added in v0.21.0

func Kbd(attrs attrs.Props, children ...Node) *Element

Kbd creates a <kbd> element.

func Label added in v0.3.0

func Label(attrs attrs.Props, children ...Node) *Element

Label creates a <label> element.

func Legend added in v0.10.0

func Legend(attrs attrs.Props, children ...Node) *Element

Legend creates a <legend> element.

func Li

func Li(attrs attrs.Props, children ...Node) *Element

Li creates an <li> element.

func Link(attrs attrs.Props) *Element

Link creates a <link> element.

func Main added in v0.7.0

func Main(attrs attrs.Props, children ...Node) *Element

Main creates a <main> element.

func Map added in v0.18.0

func Map(attrs attrs.Props, children ...Node) *Element

Map creates a <map> element.

func Mark added in v0.10.0

func Mark(attrs attrs.Props, children ...Node) *Element

Mark creates a <mark> element.

func Menu(attrs attrs.Props, children ...Node) *Element

Menu creates a <menu> element.

func Meta

func Meta(attrs attrs.Props) *Element

Meta creates a <meta> element.

func Meter added in v0.10.0

func Meter(attrs attrs.Props, children ...Node) *Element

Meter creates a <meter> element.

func Nav(attrs attrs.Props, children ...Node) *Element

Nav creates a <nav> element.

func NoScript added in v0.10.0

func NoScript(attrs attrs.Props, children ...Node) *Element

NoScript creates a <noscript> element.

func Ol added in v0.7.0

func Ol(attrs attrs.Props, children ...Node) *Element

Ol creates an <ol> element.

func Optgroup added in v0.17.0

func Optgroup(attrs attrs.Props, children ...Node) *Element

Optgroup creates an <optgroup> element to group <option>s within a <select> element.

func Option added in v0.3.0

func Option(attrs attrs.Props, content TextNode) *Element

Option creates an <option> element.

func Output added in v0.10.0

func Output(attrs attrs.Props, children ...Node) *Element

Output creates an <output> element.

func P

func P(attrs attrs.Props, children ...Node) *Element

P creates a <p> element.

func Pre added in v0.2.0

func Pre(attrs attrs.Props, children ...Node) *Element

Pre creates a <pre> element.

func Progress added in v0.10.0

func Progress(attrs attrs.Props, children ...Node) *Element

Progress creates a <progress> element.

func Q added in v0.21.0

func Q(attrs attrs.Props, children ...Node) *Element

Q creates a <q> element.

func Rp added in v0.21.0

func Rp(attrs attrs.Props, children ...Node) *Element

Rp creates a <rp> element.

func Rt added in v0.21.0

func Rt(attrs attrs.Props, children ...Node) *Element

Rt creates a <rt> element.

func Ruby added in v0.21.0

func Ruby(attrs attrs.Props, children ...Node) *Element

Ruby creates a <ruby> element.

func Samp added in v0.21.0

func Samp(attrs attrs.Props, children ...Node) *Element

Samp creates a <samp> element.

func Script

func Script(attrs attrs.Props, children ...Node) *Element

Script creates a <script> element.

func Section added in v0.7.0

func Section(attrs attrs.Props, children ...Node) *Element

Section creates a <section> element.

func Select added in v0.3.0

func Select(attrs attrs.Props, children ...Node) *Element

Select creates a <select> element.

func Small added in v0.21.0

func Small(attrs attrs.Props, children ...Node) *Element

Small creates a <small> element.

func Source added in v0.13.0

func Source(attrs attrs.Props, children ...Node) *Element

Source creates a <source> element.

func Span

func Span(attrs attrs.Props, children ...Node) *Element

Span creates a <span> element.

func Strong added in v0.2.0

func Strong(attrs attrs.Props, children ...Node) *Element

Strong creates a <strong> element.

func Style

func Style(attrs attrs.Props, children ...Node) *Element

Style creates a <style> element.

func Sub added in v0.21.0

func Sub(attrs attrs.Props, children ...Node) *Element

Sub creates a <sub> element.

func Summary added in v0.10.0

func Summary(attrs attrs.Props, children ...Node) *Element

Summary creates a <summary> element.

func Sup added in v0.21.0

func Sup(attrs attrs.Props, children ...Node) *Element

Sup creates a <sub> element.

func TBody added in v0.8.0

func TBody(attrs attrs.Props, children ...Node) *Element

TBody creates a <tbody> element.

func TFoot added in v0.8.0

func TFoot(attrs attrs.Props, children ...Node) *Element

TFoot creates a <tfoot> element.

func THead added in v0.8.0

func THead(attrs attrs.Props, children ...Node) *Element

THead creates a <thead> element.

func Table added in v0.8.0

func Table(attrs attrs.Props, children ...Node) *Element

Table creates a <table> element.

func Td added in v0.8.0

func Td(attrs attrs.Props, children ...Node) *Element

Td creates a <td> element.

func Textarea added in v0.3.0

func Textarea(attrs attrs.Props, content TextNode) *Element

Textarea creates a <textarea> element.

func Th added in v0.8.0

func Th(attrs attrs.Props, children ...Node) *Element

Th creates a <th> element.

func Time added in v0.10.0

func Time(attrs attrs.Props, children ...Node) *Element

Time creates a <time> element.

func Title

func Title(attrs attrs.Props, children ...Node) *Element

Title creates a <title> element.

func Tr added in v0.8.0

func Tr(attrs attrs.Props, children ...Node) *Element

Tr creates a <tr> element.

func U added in v0.21.0

func U(attrs attrs.Props, children ...Node) *Element

U creates a <u> element.

func Ul

func Ul(attrs attrs.Props, children ...Node) *Element

Ul creates a <ul> element.

func Var added in v0.21.0

func Var(attrs attrs.Props, children ...Node) *Element

Var creates a <var> element.

func Video added in v0.13.0

func Video(attrs attrs.Props, children ...Node) *Element

Video creates a <video> element.

func (*Element) Render

func (e *Element) Render() string

func (*Element) RenderTo added in v0.4.0

func (e *Element) RenderTo(builder *strings.Builder, opts RenderOptions)

func (*Element) RenderWithOptions added in v0.17.0

func (e *Element) RenderWithOptions(opts RenderOptions) string

type Node added in v0.5.0

type Node interface {
	RenderTo(builder *strings.Builder, opts RenderOptions)
	Render() string
	RenderWithOptions(opts RenderOptions) string
}

func TransformEach

func TransformEach[T any](items []T, fn func(T) Node) []Node

TransformEach maps a slice of items to a slice of Elements using the provided function

type NoneNode added in v0.16.0

type NoneNode struct{}

NoneNode represents a node that renders nothing.

func None added in v0.16.0

func None() NoneNode

None creates a NoneNode, representing a no-operation in rendering.

func (NoneNode) Render added in v0.16.0

func (n NoneNode) Render() string

Render for NoneNode returns an empty string.

func (NoneNode) RenderTo added in v0.16.0

func (n NoneNode) RenderTo(builder *strings.Builder, opts RenderOptions)

RenderTo for NoneNode does nothing.

func (NoneNode) RenderWithOptions added in v0.17.0

func (n NoneNode) RenderWithOptions(opts RenderOptions) string

RenderWithOptions for NoneNode returns an empty string.

type RawNode added in v0.15.0

type RawNode string

func Raw added in v0.15.0

func Raw(html string) RawNode

Raw takes html content and returns a RawNode.

func (RawNode) Render added in v0.15.0

func (r RawNode) Render() string

func (RawNode) RenderTo added in v0.15.0

func (r RawNode) RenderTo(builder *strings.Builder, opts RenderOptions)

func (RawNode) RenderWithOptions added in v0.17.0

func (t RawNode) RenderWithOptions(opts RenderOptions) string

type RenderOptions added in v0.17.0

type RenderOptions struct {
	// DisableHtmlPreamble disables the doctype preamble for the HTML tag if it exists in the rendering tree
	DisableHtmlPreamble bool
	StyleManager        CSSGenerator
}

type TextNode added in v0.5.0

type TextNode string

func CSS added in v0.22.0

func CSS(content string) TextNode

CSS takes css content and returns a TextNode.

func Text

func Text(content string) TextNode

Text creates a TextNode.

func (TextNode) Render added in v0.5.0

func (t TextNode) Render() string

func (TextNode) RenderTo added in v0.5.0

func (t TextNode) RenderTo(builder *strings.Builder, opts RenderOptions)

func (TextNode) RenderWithOptions added in v0.17.0

func (t TextNode) RenderWithOptions(opts RenderOptions) string

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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