htmlgo

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Jul 26, 2026 License: MIT Imports: 8 Imported by: 0

README

htmlgo

Type safe and modularize way to generate html on server side. Download the package with go get -v github.com/r0vx/htmlgo and import the package with . gives you simpler code:

import (
	. "github.com/r0vx/htmlgo"
)

also checkout full API documentation at: https://godoc.org/github.com/r0vx/htmlgo

Create a simple div, Text will be escaped by html

	banner := "We write html in Go"
	comp := Div(
	    Text("123<h1>"),
	    Textf("Hello, %s", banner),
	    Br(),
	)
	Fprint(os.Stdout, comp, context.TODO())
	//Output:
	// <div>123&lt;h1&gt;Hello, We write html in Go<br></div>

Create a full html page

	comp := HTML(
	    Head(
	        Meta().Charset("utf8"),
	        Title("My test page"),
	    ),
	    Body(
	        Img("images/firefox-icon.png").Alt("My test image"),
	    ),
	)
	Fprint(os.Stdout, comp, context.TODO())
	//Output:
	// <!DOCTYPE html>
	// <html><head><meta charset='utf8'><title>My test page</title></head><body><img src='images/firefox-icon.png' alt='My test image'></body></html>

Use RawHTML and Component

	userProfile := func(username string, avatarURL string) HTMLComponent {
	    return ComponentFunc(func(ctx context.Context, buf *[]byte) error {
	        return Div(
	            H1(username).Class("profileName"),
	            Img(avatarURL).Class("profileImage"),
	            RawHTML("<svg>complicated svg</svg>\n"),
	        ).Class("userProfile").MarshalHTML(ctx, buf)
	    })
	}

	comp := Ul(
	    Li(
	        userProfile("felix<h1>", "http://image.com/img1.png"),
	    ),
	    Li(
	        userProfile("john", "http://image.com/img2.png"),
	    ),
	)
	Fprint(os.Stdout, comp, context.TODO())
	//Output:
	// <ul><li><div class='userProfile'><h1 class='profileName'>felix&lt;h1&gt;</h1><img src='http://image.com/img1.png' class='profileImage'><svg>complicated svg</svg>
	// </div></li><li><div class='userProfile'><h1 class='profileName'>john</h1><img src='http://image.com/img2.png' class='profileImage'><svg>complicated svg</svg>
	// </div></li></ul>

More complicated customized component

	/*
	    Define MySelect as follows:

	    type MySelectBuilder struct {
	        options  [][]string
	        selected string
	    }

	    func MySelect() *MySelectBuilder {
	        return &MySelectBuilder{}
	    }

	    func (b *MySelectBuilder) Options(opts [][]string) (r *MySelectBuilder) {
	        b.options = opts
	        return b
	    }

	    func (b *MySelectBuilder) Selected(selected string) (r *MySelectBuilder) {
	        b.selected = selected
	        return b
	    }

	    func (b *MySelectBuilder) MarshalHTML(ctx context.Context, buf *[]byte) error {
	        opts := []HTMLComponent{}
	        for _, op := range b.options {
	            var opt HTMLComponent
	            if op[0] == b.selected {
	                opt = Option(op[1]).Value(op[0]).Attr("selected", "true")
	            } else {
	                opt = Option(op[1]).Value(op[0])
	            }
	            opts = append(opts, opt)
	        }
	        return Select(opts...).MarshalHTML(ctx, buf)
	    }
	*/

	comp := MySelect().Options([][]string{
	    {"1", "label 1"},
	    {"2", "label 2"},
	    {"3", "label 3"},
	}).Selected("2")

	Fprint(os.Stdout, comp, context.TODO())
	//Output:
	// <select><option value='1'>label 1</option><option value='2' selected='true'>label 2</option><option value='3'>label 3</option></select>

Write a little bit of JavaScript and stylesheet

	comp := Div(
	    Button("Hello").Id("hello"),
	    Style(`
	.container {
	    background-color: red;
	}
	`),

	    Script(`
	var b = document.getElementById("hello")
	b.onclick = function(e){
	    alert("Hello");
	}
	`),
	).Class("container")

	Fprint(os.Stdout, comp, context.TODO())
	//Output:
	// <div class='container'><button id='hello'>Hello</button><style type='text/css'>
	// 	.container {
	// 		background-color: red;
	// 	}
	// </style><script type='text/javascript'>
	// 	var b = document.getElementById("hello")
	// 	b.onclick = function(e){
	// 		alert("Hello");
	// 	}
	// </script></div>

An example about how to integrate into http.Handler, and how to do layout, and how to use context.

	type User struct {
	    Name string
	}

	userStatus := func() HTMLComponent {
	    return ComponentFunc(func(ctx context.Context, buf *[]byte) error {
	        if currentUser, ok := ctx.Value("currentUser").(*User); ok {
	            return Div(
	                Text(currentUser.Name),
	            ).Class("username").MarshalHTML(ctx, buf)
	        }
	        return Div(Text("Login")).Class("login").MarshalHTML(ctx, buf)
	    })
	}

	myHeader := func() HTMLComponent {
	    return Div(
	        Text("header"),
	        userStatus(),
	    ).Class("header")
	}
	myFooter := func() HTMLComponent {
	    return Div(Text("footer")).Class("footer")
	}

	layout := func(in HTMLComponent) (out HTMLComponent) {
	    out = HTML(
	        Head(
	            Meta().Charset("utf8"),
	        ),
	        Body(
	            myHeader(),
	            in,
	            myFooter(),
	        ),
	    )
	    return
	}

	getLoginUserFromCookie := func(r *http.Request) *User {
	    return &User{Name: "felix"}
	}

	homeHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
	    user := getLoginUserFromCookie(r)
	    ctx := context.WithValue(context.TODO(), "currentUser", user)

	    root := Div(
	        Text("This is my home page"),
	    )

	    Fprint(w, layout(root), ctx)
	})

	w := httptest.NewRecorder()
	r := httptest.NewRequest("GET", "/", nil)
	homeHandler.ServeHTTP(w, r)

	fmt.Println(w.Body.String())

	//Output:
	// <!DOCTYPE html>
	// <html><head><meta charset='utf8'></head><body><div class='header'>header<div class='username'>felix</div></div><div>This is my home page</div><div class='footer'>footer</div></body></html>

An example show how to set different type of attributes

	type MoreData struct {
	    Name  string
	    Count int
	}
	comp := Div(
	    Input("username").
	        Type("checkbox").
	        Attr("checked", true).
	        Attr("more-data", &MoreData{Name: "felix", Count: 100}).
	        Attr("max-length", 10),
	    Input("username2").
	        Type("checkbox").
	        Attr("checked", false),
	)
	Fprint(os.Stdout, comp, context.TODO())
	//Output:
	// <div><input name='username' type='checkbox' checked more-data='{"Name":"felix","Count":100}' max-length='10'><input name='username2' type='checkbox'></div>

An example show how to set styles

	comp := Div().
	    StyleIf("background-color:red; border:1px solid red;", true).
	    StyleIf("color:blue", true)
	Fprint(os.Stdout, comp, context.TODO())
	//Output:
	// <div style='background-color:red; border:1px solid red; color:blue;'></div>

An example to use If, Iff is for body to passed in as an func for the body depends on if condition not to be nil, If is for directly passed in HTMLComponent

	type Person struct {
	    Age int
	}
	var p *Person

	name := "Leon"
	comp := Div(
	    Iff(p != nil && p.Age > 18, func() HTMLComponent {
	        return Div().Text(name + ": Age > 18")
	    }).ElseIf(p == nil, func() HTMLComponent {
	        return Div().Text("No person named " + name)
	    }).Else(func() HTMLComponent {
	        return Div().Text(name + ":Age <= 18")
	    }),
	)
	Fprint(os.Stdout, comp, context.TODO())
	//Output:
	// <div><div>No person named Leon</div></div>

Cached wraps a static, context-independent subtree (nav, footer, ...): it renders once and replays the cached bytes afterwards, skipping re-construction and re-rendering on every request.

	footer := Cached(
	    Footer(
	        P(Text("© 2026 r0vx")),
	    ).Class("site-footer"),
	)

	// 每个请求复用同一个 footer 实例,渲染成本仅一次 memcpy
	page := Div(
	    H1("Home"),
	    footer,
	)
	Fprint(os.Stdout, page, context.TODO())
	//Output:
	// <div><h1>Home</h1><footer class='site-footer'><p>© 2026 r0vx</p></footer></div>

Documentation

Overview

## htmlgo

Type safe and modularize way to generate html on server side. Download the package with `go get -v github.com/r0vx/htmlgo` and import the package with `.` gives you simpler code:

import (
	. "github.com/r0vx/htmlgo"
)

also checkout full API documentation at: https://godoc.org/github.com/r0vx/htmlgo

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Fprint

func Fprint(w io.Writer, root HTMLComponent, ctx context.Context) error

Fprint 将组件渲染后写入 w,整棵树共享一个池化 buf;稳态下渲染零 buffer 分配

Example

An example about how to integrate into http.Handler, and how to do layout, and how to use context.

type User struct {
	Name string
}

userStatus := func() HTMLComponent {
	return ComponentFunc(func(ctx context.Context, buf *[]byte) error {
		if currentUser, ok := ctx.Value("currentUser").(*User); ok {
			return Div(
				Text(currentUser.Name),
			).Class("username").MarshalHTML(ctx, buf)
		}
		return Div(Text("Login")).Class("login").MarshalHTML(ctx, buf)
	})
}

myHeader := func() HTMLComponent {
	return Div(
		Text("header"),
		userStatus(),
	).Class("header")
}
myFooter := func() HTMLComponent {
	return Div(Text("footer")).Class("footer")
}

layout := func(in HTMLComponent) (out HTMLComponent) {
	out = HTML(
		Head(
			Meta().Charset("utf8"),
		),
		Body(
			myHeader(),
			in,
			myFooter(),
		),
	)
	return
}

getLoginUserFromCookie := func(r *http.Request) *User {
	return &User{Name: "felix"}
}

homeHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
	user := getLoginUserFromCookie(r)
	ctx := context.WithValue(context.TODO(), "currentUser", user)

	root := Div(
		Text("This is my home page"),
	)

	Fprint(w, layout(root), ctx)
})

w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/", nil)
homeHandler.ServeHTTP(w, r)

fmt.Println(w.Body.String())
Output:
<!DOCTYPE html>
<html><head><meta charset='utf8'></head><body><div class='header'>header<div class='username'>felix</div></div><div>This is my home page</div><div class='footer'>footer</div></body></html>

func JSONString

func JSONString(v any) (r string)

func MustString

func MustString(root HTMLComponent, ctx context.Context) string

MustString 将组件渲染为字符串,panic on error

Types

type ComponentFunc

type ComponentFunc func(ctx context.Context, buf *[]byte) error
Example

Use RawHTML and Component

userProfile := func(username string, avatarURL string) HTMLComponent {
	return ComponentFunc(func(ctx context.Context, buf *[]byte) error {
		return Div(
			H1(username).Class("profileName"),
			Img(avatarURL).Class("profileImage"),
			RawHTML("<svg>complicated svg</svg>\n"),
		).Class("userProfile").MarshalHTML(ctx, buf)
	})
}

comp := Ul(
	Li(
		userProfile("felix<h1>", "http://image.com/img1.png"),
	),
	Li(
		userProfile("john", "http://image.com/img2.png"),
	),
)
Fprint(os.Stdout, comp, context.TODO())
Output:
<ul><li><div class='userProfile'><h1 class='profileName'>felix&lt;h1&gt;</h1><img src='http://image.com/img1.png' class='profileImage'><svg>complicated svg</svg>
</div></li><li><div class='userProfile'><h1 class='profileName'>john</h1><img src='http://image.com/img2.png' class='profileImage'><svg>complicated svg</svg>
</div></li></ul>

func (ComponentFunc) MarshalHTML

func (f ComponentFunc) MarshalHTML(ctx context.Context, buf *[]byte) error

type HTMLComponent

type HTMLComponent interface {
	MarshalHTML(ctx context.Context, buf *[]byte) error
}

func Cached added in v0.2.0

func Cached(comp HTMLComponent) HTMLComponent

Cached 包装一个与 ctx 无关的静态组件:首次渲染后缓存字节,之后纯拷贝输出。 适合导航、footer 等每请求重复构建的不变子树;被包装组件的输出若依赖 ctx 或可变状态则不要使用。并发安全。

Example

Cached wraps a static, context-independent subtree (nav, footer, ...): it renders once and replays the cached bytes afterwards, skipping re-construction and re-rendering on every request.

footer := Cached(
	Footer(
		P(Text("© 2026 r0vx")),
	).Class("site-footer"),
)

// 每个请求复用同一个 footer 实例,渲染成本仅一次 memcpy
page := Div(
	H1("Home"),
	footer,
)
Fprint(os.Stdout, page, context.TODO())
Output:
<div><h1>Home</h1><footer class='site-footer'><p>© 2026 r0vx</p></footer></div>

func HTML

func HTML(children ...HTMLComponent) (r HTMLComponent)

"html": HTMLHtmlElement;

Example

Create a full html page

comp := HTML(
	Head(
		Meta().Charset("utf8"),
		Title("My test page"),
	),
	Body(
		Img("images/firefox-icon.png").Alt("My test image"),
	),
)
Fprint(os.Stdout, comp, context.TODO())
Output:
<!DOCTYPE html>
<html><head><meta charset='utf8'><title>My test page</title></head><body><img src='images/firefox-icon.png' alt='My test image'></body></html>

func Interp added in v1.1.0

func Interp(expr string) HTMLComponent

Interp 在服务端 HTML 里内联 Vue 模板插值(`{{ expr }}`),原样输出、不转义。 ⚠️ 绝不可用于用户数据——用户数据一律走 Text(默认中和 `{{`,防模板注入 / 客户端 XSS)。 expr 应是受信的框架/前端表达式(如 "{{locals.count}}"、"{{element.label}}")。

func Text

func Text(text string) (r HTMLComponent)

func Textf

func Textf(format string, a ...any) (r HTMLComponent)

type HTMLComponents

type HTMLComponents []HTMLComponent

func Components

func Components(comps ...HTMLComponent) HTMLComponents
Example

More complicated customized component

/*
	Define MySelect as follows:

	type MySelectBuilder struct {
		options  [][]string
		selected string
	}

	func MySelect() *MySelectBuilder {
		return &MySelectBuilder{}
	}

	func (b *MySelectBuilder) Options(opts [][]string) (r *MySelectBuilder) {
		b.options = opts
		return b
	}

	func (b *MySelectBuilder) Selected(selected string) (r *MySelectBuilder) {
		b.selected = selected
		return b
	}

	func (b *MySelectBuilder) MarshalHTML(ctx context.Context, buf *[]byte) error {
		opts := []HTMLComponent{}
		for _, op := range b.options {
			var opt HTMLComponent
			if op[0] == b.selected {
				opt = Option(op[1]).Value(op[0]).Attr("selected", "true")
			} else {
				opt = Option(op[1]).Value(op[0])
			}
			opts = append(opts, opt)
		}
		return Select(opts...).MarshalHTML(ctx, buf)
	}
*/

comp := MySelect().Options([][]string{
	{"1", "label 1"},
	{"2", "label 2"},
	{"3", "label 3"},
}).Selected("2")

Fprint(os.Stdout, comp, context.TODO())
Output:
<select><option value='1'>label 1</option><option value='2' selected='true'>label 2</option><option value='3'>label 3</option></select>

func (HTMLComponents) MarshalHTML

func (hcs HTMLComponents) MarshalHTML(ctx context.Context, buf *[]byte) error

type HTMLTagBuilder

type HTMLTagBuilder struct {
	// contains filtered or unexported fields
}

HTMLTagBuilder 不可值拷贝:classNames 初始指向内联的 classBuf, 值拷贝会让两个 builder 共享同一底层数组 字段经基准调优:结构体大小(分配清零 + GC 扫描)比分配次数对耗时影响更大, 故只内联收益最高的单个 class 槽,不内联 attrs

func A

func A(children ...HTMLComponent) (r *HTMLTagBuilder)

"a": HTMLAnchorElement;

func Abbr

func Abbr(text string) (r *HTMLTagBuilder)

"abbr": HTMLElement;

func Address

func Address(children ...HTMLComponent) (r *HTMLTagBuilder)

"address": HTMLElement;

func Area

func Area() (r *HTMLTagBuilder)

"area": HTMLAreaElement;

func Article

func Article(children ...HTMLComponent) (r *HTMLTagBuilder)

"article": HTMLElement;

func Aside

func Aside(children ...HTMLComponent) (r *HTMLTagBuilder)

"aside": HTMLElement;

func Audio

func Audio(children ...HTMLComponent) (r *HTMLTagBuilder)

"audio": HTMLAudioElement;

func B

func B(text string) (r *HTMLTagBuilder)

"b": HTMLElement;

func Base

func Base() (r *HTMLTagBuilder)

"base": HTMLBaseElement;

func Bdi

func Bdi(text string) (r *HTMLTagBuilder)

"bdi": HTMLElement;

func Bdo

func Bdo(text string) (r *HTMLTagBuilder)

"bdo": HTMLElement;

func Blockquote

func Blockquote(children ...HTMLComponent) (r *HTMLTagBuilder)

"blockquote": HTMLQuoteElement;

func Body

func Body(children ...HTMLComponent) (r *HTMLTagBuilder)

"body": HTMLBodyElement;

func Br

func Br() (r *HTMLTagBuilder)

"br": HTMLBRElement;

func Button

func Button(label string) (r *HTMLTagBuilder)

"button": HTMLButtonElement;

func Canvas

func Canvas(children ...HTMLComponent) (r *HTMLTagBuilder)

"canvas": HTMLCanvasElement;

func Caption

func Caption(text string) (r *HTMLTagBuilder)

"caption": HTMLTableCaptionElement;

func Cite

func Cite(children ...HTMLComponent) (r *HTMLTagBuilder)

"cite": HTMLElement;

func Code

func Code(text string) (r *HTMLTagBuilder)

"code": HTMLElement;

func Col

func Col() (r *HTMLTagBuilder)

"col": HTMLTableColElement;

func Colgroup

func Colgroup(children ...HTMLComponent) (r *HTMLTagBuilder)

"colgroup": HTMLTableColElement;

func Data

func Data(children ...HTMLComponent) (r *HTMLTagBuilder)

"data": HTMLDataElement;

func Datalist

func Datalist(children ...HTMLComponent) (r *HTMLTagBuilder)

"datalist": HTMLDataListElement;

func Dd

func Dd(children ...HTMLComponent) (r *HTMLTagBuilder)

"dd": HTMLElement;

func Del

func Del(text string) (r *HTMLTagBuilder)

"del": HTMLModElement;

func Details

func Details(children ...HTMLComponent) (r *HTMLTagBuilder)

func Dfn

func Dfn(text string) (r *HTMLTagBuilder)

"dfn": HTMLElement;

func Dialog

func Dialog(children ...HTMLComponent) (r *HTMLTagBuilder)

"dialog": HTMLDialogElement;

func Div

func Div(children ...HTMLComponent) (r *HTMLTagBuilder)

"div": HTMLDivElement;

Example

Create a simple div, Text will be escaped by html

banner := "We write html in Go"
comp := Div(
	Text("123<h1>"),
	Textf("Hello, %s", banner),
	Br(),
)
Fprint(os.Stdout, comp, context.TODO())
Output:
<div>123&lt;h1&gt;Hello, We write html in Go<br></div>

func Dl

func Dl(children ...HTMLComponent) (r *HTMLTagBuilder)

"dl": HTMLDListElement;

func Dt

func Dt(children ...HTMLComponent) (r *HTMLTagBuilder)

"dt": HTMLElement;

func Em

func Em(text string) (r *HTMLTagBuilder)

"em": HTMLElement;

func Embed

func Embed() (r *HTMLTagBuilder)

"embed": HTMLEmbedElement;

func Fieldset

func Fieldset(children ...HTMLComponent) (r *HTMLTagBuilder)

"fieldset": HTMLFieldSetElement;

func Figcaption

func Figcaption(text string) (r *HTMLTagBuilder)

"figcaption": HTMLElement;

func Figure

func Figure(children ...HTMLComponent) (r *HTMLTagBuilder)

"figure": HTMLElement;

func Footer(children ...HTMLComponent) (r *HTMLTagBuilder)

"footer": HTMLElement;

func Form

func Form(children ...HTMLComponent) (r *HTMLTagBuilder)

"form": HTMLFormElement;

func H1

func H1(text string) (r *HTMLTagBuilder)

"h1": HTMLHeadingElement;

func H2

func H2(text string) (r *HTMLTagBuilder)

"h2": HTMLHeadingElement;

func H3

func H3(text string) (r *HTMLTagBuilder)

"h3": HTMLHeadingElement;

func H4

func H4(text string) (r *HTMLTagBuilder)

"h4": HTMLHeadingElement;

func H5

func H5(text string) (r *HTMLTagBuilder)

"h5": HTMLHeadingElement;

func H6

func H6(text string) (r *HTMLTagBuilder)

"h6": HTMLHeadingElement;

func Head(children ...HTMLComponent) (r *HTMLTagBuilder)
func Header(children ...HTMLComponent) (r *HTMLTagBuilder)

"header": HTMLElement;

func Hgroup

func Hgroup(children ...HTMLComponent) (r *HTMLTagBuilder)

"hgroup": HTMLElement;

func Hr

func Hr() (r *HTMLTagBuilder)

"hr": HTMLHRElement;

func I

func I(text string) (r *HTMLTagBuilder)

"i": HTMLElement;

func Iframe

func Iframe(children ...HTMLComponent) (r *HTMLTagBuilder)

"iframe": HTMLIFrameElement;

func Img

func Img(src string) (r *HTMLTagBuilder)

"img": HTMLImageElement;

func Input

func Input(name string) (r *HTMLTagBuilder)

func Ins

func Ins(children ...HTMLComponent) (r *HTMLTagBuilder)

"ins": HTMLModElement;

func Kbd

func Kbd(text string) (r *HTMLTagBuilder)

"kbd": HTMLElement;

func Label

func Label(text string) (r *HTMLTagBuilder)

"label": HTMLLabelElement;

func Legend

func Legend(text string) (r *HTMLTagBuilder)

"legend": HTMLLegendElement;

func Li

func Li(children ...HTMLComponent) (r *HTMLTagBuilder)

"li": HTMLLIElement;

func Link(href string) (r *HTMLTagBuilder)

"link": HTMLLinkElement;

func Main

func Main(children ...HTMLComponent) (r *HTMLTagBuilder)

"main": HTMLElement;

func Map

func Map(children ...HTMLComponent) (r *HTMLTagBuilder)

"map": HTMLMapElement;

func Mark

func Mark(text string) (r *HTMLTagBuilder)

"mark": HTMLElement;

func Menu(children ...HTMLComponent) (r *HTMLTagBuilder)

"menu": HTMLMenuElement;

func Meta

func Meta() (r *HTMLTagBuilder)

func Meter

func Meter(children ...HTMLComponent) (r *HTMLTagBuilder)

"meter": HTMLMeterElement;

func Nav(children ...HTMLComponent) (r *HTMLTagBuilder)

"nav": HTMLElement;

func Noscript

func Noscript(children ...HTMLComponent) (r *HTMLTagBuilder)

"noscript": HTMLElement;

func Object

func Object(data string) (r *HTMLTagBuilder)

"object": HTMLObjectElement;

func Ol

func Ol(children ...HTMLComponent) (r *HTMLTagBuilder)

"ol": HTMLOListElement;

func Optgroup

func Optgroup(children ...HTMLComponent) (r *HTMLTagBuilder)

"optgroup": HTMLOptGroupElement;

func Option

func Option(text string) (r *HTMLTagBuilder)

"option": HTMLOptionElement;

func Output

func Output(children ...HTMLComponent) (r *HTMLTagBuilder)

"output": HTMLOutputElement;

func P

func P(children ...HTMLComponent) (r *HTMLTagBuilder)

"p": HTMLParagraphElement;

func Param

func Param(name string) (r *HTMLTagBuilder)

"param": HTMLParamElement;

func Picture

func Picture(children ...HTMLComponent) (r *HTMLTagBuilder)

"picture": HTMLPictureElement;

func Pre

func Pre(text string) (r *HTMLTagBuilder)

"pre": HTMLPreElement;

func Progress

func Progress(children ...HTMLComponent) (r *HTMLTagBuilder)

"progress": HTMLProgressElement;

func Q

func Q(text string) (r *HTMLTagBuilder)

"q": HTMLQuoteElement;

func Rp

func Rp(text string) (r *HTMLTagBuilder)

"rp": HTMLElement;

func Rt

func Rt(text string) (r *HTMLTagBuilder)

"rt": HTMLElement;

func Ruby

func Ruby(children ...HTMLComponent) (r *HTMLTagBuilder)

"ruby": HTMLElement;

func S

func S(text string) (r *HTMLTagBuilder)

"s": HTMLElement;

func Samp

func Samp(children ...HTMLComponent) (r *HTMLTagBuilder)

func Script

func Script(script string) (r *HTMLTagBuilder)

"script": HTMLScriptElement;

Example

Write a little bit of JavaScript and stylesheet

comp := Div(
	Button("Hello").Id("hello"),
	Style(`
	.container {
		background-color: red;
	}
`),

	Script(`
	var b = document.getElementById("hello")
	b.onclick = function(e){
		alert("Hello");
	}
`),
).Class("container")

Fprint(os.Stdout, comp, context.TODO())
Output:
<div class='container'><button id='hello'>Hello</button><style type='text/css'>
	.container {
		background-color: red;
	}
</style><script type='text/javascript'>
	var b = document.getElementById("hello")
	b.onclick = function(e){
		alert("Hello");
	}
</script></div>

func Section

func Section(children ...HTMLComponent) (r *HTMLTagBuilder)

"section": HTMLElement;

func Select

func Select(children ...HTMLComponent) (r *HTMLTagBuilder)

"select": HTMLSelectElement;

func Slot

func Slot(children ...HTMLComponent) (r *HTMLTagBuilder)

"slot": HTMLSlotElement;

func Small

func Small(text string) (r *HTMLTagBuilder)

"small": HTMLElement;

func Source

func Source(src string) (r *HTMLTagBuilder)

"source": HTMLSourceElement;

func Span

func Span(text string) (r *HTMLTagBuilder)

"span": HTMLSpanElement;

func Strong

func Strong(text string) (r *HTMLTagBuilder)

"strong": HTMLElement;

func Style

func Style(style string) (r *HTMLTagBuilder)

"style": HTMLStyleElement;

func Sub

func Sub(text string) (r *HTMLTagBuilder)

"sub": HTMLElement;

func Summary

func Summary(children ...HTMLComponent) (r *HTMLTagBuilder)

"summary": HTMLElement;

func Sup

func Sup(text string) (r *HTMLTagBuilder)

"sup": HTMLElement;

func Table

func Table(children ...HTMLComponent) (r *HTMLTagBuilder)

"table": HTMLTableElement;

func Tag

func Tag(tag string) (r *HTMLTagBuilder)

func Tbody

func Tbody(children ...HTMLComponent) (r *HTMLTagBuilder)

"tbody": HTMLTableSectionElement;

func Td

func Td(children ...HTMLComponent) (r *HTMLTagBuilder)

"td": HTMLTableDataCellElement;

func Template

func Template(children ...HTMLComponent) (r *HTMLTagBuilder)

"template": HTMLTemplateElement;

func Textarea

func Textarea(text string) (r *HTMLTagBuilder)

"textarea": HTMLTextAreaElement;

func Tfoot

func Tfoot(children ...HTMLComponent) (r *HTMLTagBuilder)

"tfoot": HTMLTableSectionElement;

func Th

func Th(text string) (r *HTMLTagBuilder)

"th": HTMLTableHeaderCellElement;

func Thead

func Thead(children ...HTMLComponent) (r *HTMLTagBuilder)

"thead": HTMLTableSectionElement;

func Time

func Time(datetime string) (r *HTMLTagBuilder)

"time": HTMLTimeElement;

func Title

func Title(text string) (r *HTMLTagBuilder)

"title": HTMLTitleElement;

func Tr

func Tr(children ...HTMLComponent) (r *HTMLTagBuilder)

"tr": HTMLTableRowElement;

func Track

func Track(src string) (r *HTMLTagBuilder)

"track": HTMLTrackElement;

func U

func U(text string) (r *HTMLTagBuilder)

"u": HTMLElement;

func Ul

func Ul(children ...HTMLComponent) (r *HTMLTagBuilder)

"ul": HTMLUListElement;

func Var

func Var(text string) (r *HTMLTagBuilder)

"var": HTMLElement;

func Video

func Video(children ...HTMLComponent) (r *HTMLTagBuilder)

"video": HTMLVideoElement;

func Wbr

func Wbr() (r *HTMLTagBuilder)

"wbr": HTMLElement;

func (*HTMLTagBuilder) Action

func (b *HTMLTagBuilder) Action(v string) (r *HTMLTagBuilder)

func (*HTMLTagBuilder) Alt

func (b *HTMLTagBuilder) Alt(v string) (r *HTMLTagBuilder)

func (*HTMLTagBuilder) AppendChildren

func (b *HTMLTagBuilder) AppendChildren(c ...HTMLComponent) (r *HTMLTagBuilder)

func (*HTMLTagBuilder) Attr

func (b *HTMLTagBuilder) Attr(vs ...any) (r *HTMLTagBuilder)
Example

An example show how to set different type of attributes

type MoreData struct {
	Name  string
	Count int
}
comp := Div(
	Input("username").
		Type("checkbox").
		Attr("checked", true).
		Attr("more-data", &MoreData{Name: "felix", Count: 100}).
		Attr("max-length", 10),
	Input("username2").
		Type("checkbox").
		Attr("checked", false),
)
Fprint(os.Stdout, comp, context.TODO())
Output:
<div><input name='username' type='checkbox' checked more-data='{"Name":"felix","Count":100}' max-length='10'><input name='username2' type='checkbox'></div>

func (*HTMLTagBuilder) AttrIf

func (b *HTMLTagBuilder) AttrIf(key, value any, add bool) (r *HTMLTagBuilder)

func (*HTMLTagBuilder) Charset

func (b *HTMLTagBuilder) Charset(v string) (r *HTMLTagBuilder)

func (*HTMLTagBuilder) Checked

func (b *HTMLTagBuilder) Checked(v bool) (r *HTMLTagBuilder)

func (*HTMLTagBuilder) Children

func (b *HTMLTagBuilder) Children(comps ...HTMLComponent) (r *HTMLTagBuilder)

func (*HTMLTagBuilder) Class

func (b *HTMLTagBuilder) Class(names ...string) (r *HTMLTagBuilder)

func (*HTMLTagBuilder) ClassIf

func (b *HTMLTagBuilder) ClassIf(name string, add bool) (r *HTMLTagBuilder)

func (*HTMLTagBuilder) Content

func (b *HTMLTagBuilder) Content(v string) (r *HTMLTagBuilder)

func (*HTMLTagBuilder) Data

func (b *HTMLTagBuilder) Data(vs ...string) (r *HTMLTagBuilder)

func (*HTMLTagBuilder) Disabled

func (b *HTMLTagBuilder) Disabled(v bool) (r *HTMLTagBuilder)

func (*HTMLTagBuilder) For

func (b *HTMLTagBuilder) For(v string) (r *HTMLTagBuilder)

func (*HTMLTagBuilder) Href

func (b *HTMLTagBuilder) Href(v string) (r *HTMLTagBuilder)

func (*HTMLTagBuilder) Id

func (b *HTMLTagBuilder) Id(v string) (r *HTMLTagBuilder)

func (*HTMLTagBuilder) MarshalHTML

func (b *HTMLTagBuilder) MarshalHTML(ctx context.Context, buf *[]byte) error

func (*HTMLTagBuilder) Method

func (b *HTMLTagBuilder) Method(v string) (r *HTMLTagBuilder)

func (*HTMLTagBuilder) Name

func (b *HTMLTagBuilder) Name(v string) (r *HTMLTagBuilder)

func (*HTMLTagBuilder) OmitEndTag

func (b *HTMLTagBuilder) OmitEndTag() (r *HTMLTagBuilder)

func (*HTMLTagBuilder) Placeholder

func (b *HTMLTagBuilder) Placeholder(v string) (r *HTMLTagBuilder)

func (*HTMLTagBuilder) PrependChildren

func (b *HTMLTagBuilder) PrependChildren(c ...HTMLComponent) (r *HTMLTagBuilder)

func (*HTMLTagBuilder) Property

func (b *HTMLTagBuilder) Property(v string) (r *HTMLTagBuilder)

func (*HTMLTagBuilder) Readonly

func (b *HTMLTagBuilder) Readonly(v bool) (r *HTMLTagBuilder)

func (*HTMLTagBuilder) Rel

func (b *HTMLTagBuilder) Rel(v string) (r *HTMLTagBuilder)

func (*HTMLTagBuilder) Required

func (b *HTMLTagBuilder) Required(v bool) (r *HTMLTagBuilder)

func (*HTMLTagBuilder) Role

func (b *HTMLTagBuilder) Role(v string) (r *HTMLTagBuilder)

func (*HTMLTagBuilder) SetAttr

func (b *HTMLTagBuilder) SetAttr(k string, v any)

func (*HTMLTagBuilder) Src

func (b *HTMLTagBuilder) Src(v string) (r *HTMLTagBuilder)

func (*HTMLTagBuilder) Style

func (b *HTMLTagBuilder) Style(v string) (r *HTMLTagBuilder)
Example

An example show how to set styles

comp := Div().
	StyleIf("background-color:red; border:1px solid red;", true).
	StyleIf("color:blue", true)
Fprint(os.Stdout, comp, context.TODO())
Output:
<div style='background-color:red; border:1px solid red; color:blue;'></div>

func (*HTMLTagBuilder) StyleIf

func (b *HTMLTagBuilder) StyleIf(v string, add bool) (r *HTMLTagBuilder)

func (*HTMLTagBuilder) TabIndex

func (b *HTMLTagBuilder) TabIndex(v int) (r *HTMLTagBuilder)

func (*HTMLTagBuilder) Tag

func (b *HTMLTagBuilder) Tag(v string) (r *HTMLTagBuilder)

func (*HTMLTagBuilder) Target

func (b *HTMLTagBuilder) Target(v string) (r *HTMLTagBuilder)

func (*HTMLTagBuilder) Text

func (b *HTMLTagBuilder) Text(v string) (r *HTMLTagBuilder)

func (*HTMLTagBuilder) Title

func (b *HTMLTagBuilder) Title(v string) (r *HTMLTagBuilder)

func (*HTMLTagBuilder) Type

func (b *HTMLTagBuilder) Type(v string) (r *HTMLTagBuilder)

func (*HTMLTagBuilder) Value

func (b *HTMLTagBuilder) Value(v string) (r *HTMLTagBuilder)

type IfBuilder

type IfBuilder struct {
	// contains filtered or unexported fields
}

func If

func If(v bool, comps ...HTMLComponent) (r *IfBuilder)

func (*IfBuilder) Else

func (b *IfBuilder) Else(comps ...HTMLComponent) (r *IfBuilder)

func (*IfBuilder) ElseIf

func (b *IfBuilder) ElseIf(v bool, comps ...HTMLComponent) (r *IfBuilder)

func (*IfBuilder) MarshalHTML

func (b *IfBuilder) MarshalHTML(ctx context.Context, buf *[]byte) error

type IfFuncBuilder

type IfFuncBuilder struct {
	// contains filtered or unexported fields
}

func Iff

func Iff(v bool, f func() HTMLComponent) (r *IfFuncBuilder)
Example

An example to use If, `Iff` is for body to passed in as an func for the body depends on if condition not to be nil, `If` is for directly passed in HTMLComponent

type Person struct {
	Age int
}
var p *Person

name := "Leon"
comp := Div(
	Iff(p != nil && p.Age > 18, func() HTMLComponent {
		return Div().Text(name + ": Age > 18")
	}).ElseIf(p == nil, func() HTMLComponent {
		return Div().Text("No person named " + name)
	}).Else(func() HTMLComponent {
		return Div().Text(name + ":Age <= 18")
	}),
)
Fprint(os.Stdout, comp, context.TODO())
Output:
<div><div>No person named Leon</div></div>

func (*IfFuncBuilder) Else

func (b *IfFuncBuilder) Else(f func() HTMLComponent) (r *IfFuncBuilder)

func (*IfFuncBuilder) ElseIf

func (b *IfFuncBuilder) ElseIf(v bool, f func() HTMLComponent) (r *IfFuncBuilder)

func (*IfFuncBuilder) MarshalHTML

func (b *IfFuncBuilder) MarshalHTML(ctx context.Context, buf *[]byte) error

type MutableAttrHTMLComponent

type MutableAttrHTMLComponent interface {
	HTMLComponent
	SetAttr(k string, v any)
}

type RawHTML

type RawHTML string

func (RawHTML) MarshalHTML

func (s RawHTML) MarshalHTML(ctx context.Context, buf *[]byte) error

Jump to

Keyboard shortcuts

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