html5tag

package module
v1.0.3 Latest Latest
Warning

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

Go to latest
Published: Dec 10, 2023 License: MIT Imports: 13 Imported by: 17

README

Go Reference Build Status Go Report Card codecov

html5tag

The html5tag package contains utilities to generate html 5 tags. Choose between string versions of the functions for easy tag creation, or io.Writer versions for speed.

html5tag also has a tag builder for convenience and can perform math operations on numeric style values.

html5tag does some checks to make sure tags are well-formed. For example, when adding data-* attributes, it will make sure the key used for the attribute does not violate html syntax rules.

html5tag has options to pretty-print tags and the content of tags so they appear formatted in a document. However, in certain contexts, like in inline text, or in a textarea tag, adding extra returns and spaces changes the look of the output. In these situations, use the functions that do not add spaces to the inner HTML of a tag.

Some examples:

package main

import . "github.com/goradd/html5tag"

main() {
	
	// Render an input tag, inside a div tag, inside a body tag using different tag building mechanisms

	a := NewAttributes().
	SetID("myText").
	Set("text", "Hi there").
	Set("placeholder", "Write here").
	SetClass("class1 class2").
	SetStyle("width":"20em")
	
	inputTag := RenderVoidTag("input", a)
	divTag := RenderTag("div", Attriubtes{"id":"inputWrapper"}, inputTag)
	
	bodyTag := NewTagBuilder().
		Tag("body").
		ID("bodyId").
		InnerHtml(divTag).
		String()
	
	fmt.Print(bodyTag)
}

For complete documentation, start at the documentation for RenderTag() and WriteTag() and drill down from there.

Documentation

Overview

Package html5tag includes functions for manipulating html 5 formatted tags. It includes specific functions for manipulating attributes inside of tags, including various special attributes like styles, classes, and data-* attributes.

Many of the routines return a boolean to indicate whether the data actually changed. This can be used to prevent needlessly redrawing html after setting values that had no effect on the attribute list.

You can choose to build tags using strings for convenience, or io.Writer for speed.

Index

Examples

Constants

View Source
const FalseValue = "**GORADD-FALSE**"

FalseValue is use by Set to set a boolean attribute to false. The Has() function will return true, but the value will not appear in the attribute list when converted to a string.

Variables

This section is empty.

Functions

func Comment

func Comment(s string) string

Comment turns the given text into an HTML comment and returns the rendered comment

Example
s := Comment("This is a test")
fmt.Print(s)
Output:

<!-- This is a test -->

func HasWord

func HasWord(haystack string, needle string) (found bool)

HasWord searches haystack for the given needle.

Example
found := HasWord("myClass31 myClass2", "myClass3")
fmt.Println(strconv.FormatBool(found))
Output:

false

func HasWordWithPrefix added in v1.0.3

func HasWordWithPrefix(class string, prefix string) bool

HasWordWithPrefix returns true if the given string has a word in it with the given prefix.

func Indent

func Indent(s string) string

Indent will add space to the front of every line in the string. Since indent is used to format code for reading while we are in development mode, we do not need it to be particularly efficient. It will not do this for textarea tags, since that would change the text in the tag.

func MergeStyleStrings

func MergeStyleStrings(s1, s2 string) string

MergeStyleStrings merges the styles found in the two style strings. s2 wins conflicts.

func MergeWords

func MergeWords(originalValues string, newValues string) string

MergeWords is a utility function that appends the given space separated words to the end of the given string, if the words are not already in the string. This is primarily used for adding classes to a class attribute, but other attributes work as well, like aria-labelledby and aria-describedby attributes.

MergeWords returns the new string, which will have no duplicates.

Since the order of a class list in html makes a difference, you should take care in the order of the classes you add if this matters in your situation.

Example
classes := MergeWords("myClass1 myClass2", "myClass1 myClass3")
fmt.Println(classes)
Output:

myClass1 myClass2 myClass3

func RandomString

func RandomString(n int) string

RandomString generates a pseudo random string of the given length Characters are drawn from legal HTML values that do not need encoding. The distribution is not perfect, so it is not good for crypto, but works for general purposes. This also works for GET variables.

func RemoveClassesWithPrefix

func RemoveClassesWithPrefix(class string, prefix string) string

RemoveClassesWithPrefix will remove all classes from the class string with the given prefix.

Many CSS frameworks use families of classes, which are built up from a base family name. For example, Bootstrap uses 'col-lg-6' to represent a table that is 6 units wide on large screens and Foundation uses 'large-6' to do the same thing. This utility removes classes that start with a particular prefix to remove whatever sizing class was specified. Returns the resulting class list.

Example
classes := RemoveClassesWithPrefix("col-6 col-brk col4-other", "col-")
fmt.Println(classes)
Output:

col4-other

func RemoveWords

func RemoveWords(originalValues string, removeValues string) string

RemoveWords removes a value from the list of space-separated values given. You can give it more than one value to remove by separating the values with spaces in the removeValue string. This is particularly useful for removing a class from a class list in a class attribute.

Example
classes := RemoveWords("myClass1 myClass2", "myClass1 myClass3")
fmt.Println(classes)
Output:

myClass2

func RenderImage

func RenderImage(src string, alt string, attributes Attributes) string

RenderImage renders an image tag with the given source, alt and attribute values. Panics on error.

func RenderLabel

func RenderLabel(labelAttributes Attributes, label string, ctrlHtml string, mode LabelDrawingMode) string

RenderLabel is a utility function to render a label, together with its text. Various CSS frameworks require labels to be rendered a certain way.

Example
s1 := RenderLabel(nil, "Title", "<input>", LabelBefore)
s2 := RenderLabel(nil, "Title", "<input>", LabelAfter)
s3 := RenderLabel(nil, "Title", "<input>", LabelWrapBefore)
s4 := RenderLabel(nil, "Title", "<input>", LabelWrapAfter)
fmt.Println(s1)
fmt.Println(s2)
fmt.Println(s3)
fmt.Println(s4)
Output:

<label>Title</label> <input>
<input> <label>Title</label>
<label>
Title <input>
</label>
<label>
<input> Title
</label>

func RenderTag

func RenderTag(tag string, attr Attributes, innerHtml string) string

RenderTag renders a standard html tag with a closing tag.

innerHtml is html, and must already be escaped if needed.

The tag will be surrounded with newlines to force general formatting consistency. This will cause the tag to be rendered with a space between it and its neighbors if the tag is not a block tag.

In the few situations where you would want to get rid of this space, call RenderTagNoSpace()

func RenderTagFormatted

func RenderTagFormatted(tag string, attr Attributes, innerHtml string) string

RenderTagFormatted renders the tag, pretty prints the innerHtml and sorts the attributes.

Do not use this for tags where changing the innerHtml will change the appearance.

func RenderTagNoSpace

func RenderTagNoSpace(tag string, attr Attributes, innerHtml string) string

RenderTagNoSpace is similar to RenderTag, but should be used in situations where the tag is an inline tag that you want to visually be right next to its neighbors with no space.

Example
fmt.Println(RenderTagNoSpace("div", Attributes{"id": "me"}, "Here I am"))
Output:

<div id="me">Here I am</div>

func RenderTagNoSpaceFormatted

func RenderTagNoSpaceFormatted(tag string, attr Attributes, innerHtml string) string

RenderTagNoSpaceFormatted will render without formatting the innerHtml, but WILL sort the attributes.

func RenderVoidTag

func RenderVoidTag(tag string, attr Attributes) (s string)

RenderVoidTag renders a void tag using the given tag name and attributes.

Example
fmt.Println(RenderVoidTag("img", Attributes{"src": "thisFile"}))
Output:

<img src="thisFile">

func StyleString

func StyleString(i interface{}) string

StyleString converts an interface type that is being used to set a style value to a string that can be fed into the SetStyle* functions

func TextToHtml

func TextToHtml(in string) (out string)

TextToHtml does a variety of transformations to make standard text presentable as HTML. It escapes characters needing to be escaped and turns newlines into breaks and double newlines into paragraphs.

Example
s := TextToHtml("This is a & test.\n\nA paragraph\nwith a forced break.")
fmt.Println(s)
Output:

This is a &amp; test.<p>A paragraph<br />with a forced break.

func ToDataAttr

func ToDataAttr(s string) (string, error)

ToDataAttr is a helper function to convert a name from camelCase to kabob-case for data attributes in particular.

data-* html attributes have special conversion rules. Attribute names should always be lower case. Dashes in the name get converted to camel case javascript variable names. For example, if you want to pass the value with key name "testVar" to javascript by printing it in the html, you would use this function to help convert it to "data-test-var", after which you can retrieve in javascript by calling ".data('testVar')". on the object. This will also test for the existence of a camel case string it cannot handle

Example
s, _ := ToDataAttr("thisIsMyTest")
fmt.Println(s)
Output:

this-is-my-test

func ToDataKey

func ToDataKey(s string) (string, error)

ToDataKey is a helper function to convert a name from kabob-case to camelCase.

data-* html attributes have special conversion rules. Key names should always be lower case. Dashes in the name get converted to camel case javascript variable names. For example, if you want to pass the value with key name "testVar" to javascript by printing it in the html, you would use this function to help convert it to "data-test-var", after which you can retrieve in javascript by calling ".dataset.testVar" on the object.

func ValueString

func ValueString(i interface{}) string

ValueString is a helper function to convert an interface type to a string that is appropriate for the value in the Set function.

Example
a := Attributes{}
a.Set("a", ValueString(1))
a.Set("b", ValueString(float32(2.2)))
a.Set("c", ValueString("test"))
a.Set("d", ValueString(true))
a.Set("e", ValueString(false))
fmt.Println(a.SortedString())
Output:

a="1" b="2.2" c="test" d

func WriteImage

func WriteImage(w io.Writer, src string, alt string, attributes Attributes) (n int, err error)

WriteImage writes an image tag.

func WriteLabel

func WriteLabel(w io.Writer, labelAttributes Attributes, label string, ctrlHtml io.WriterTo, mode LabelDrawingMode) (n int, err error)

WriteLabel is a utility function to render a label, together with its text. Various CSS frameworks require labels to be rendered a certain way.

func WriteTag

func WriteTag(w io.Writer, tag string, attr Attributes, innerHtml io.WriterTo) (n int, err error)

WriteTag writes the tag to the io.Writer.

func WriteTagFormatted

func WriteTagFormatted(w io.Writer, tag string, attr Attributes, innerHtml io.WriterTo) (n int, err error)

WriteTagFormatted writes the tag to the io.Writer, pretty prints the innerHtml and sorts the attributes.

func WriteTagNoSpace

func WriteTagNoSpace(w io.Writer, tag string, attr Attributes, innerHtml io.WriterTo) (n int, err error)

WriteTagNoSpace writes the tag to the io.Writer, and does not add any spaces between the tag and the innerHtml.

func WriteTagNoSpaceFormatted

func WriteTagNoSpaceFormatted(w io.Writer, tag string, attr Attributes, innerHtml io.WriterTo) (n int, err error)

WriteTagNoSpaceFormatted writes to tag without formatting the innerHtml, but WILL sort the attributes.

func WriteVoidTag

func WriteVoidTag(w io.Writer, tag string, attr Attributes) (n int, err error)

WriteVoidTag writes a void tag to the io.Writer.

Types

type Attributer

type Attributer interface {
	Attributes(...interface{}) Attributes
}

Attributer is a general purpose interface for objects that return attributes based on information given.

type Attributes

type Attributes map[string]string

Attributes is an HTML attribute manager.

Use Set to set specific attribute values, and then convert it to a string to get the attributes embeddable in an HTML tag.

To create new attributes, the easiest is to do this:

a := Attributes{"id":"theId", "class":"myClass"}

func NewAttributes

func NewAttributes() Attributes

NewAttributes creates a new Attributes collection.

func (Attributes) AddClass

func (a Attributes) AddClass(v string) Attributes

AddClass adds a class or classes. Multiple classes can be separated by spaces. If a class is not present, the class will be added to the end of the class list. If a class is present, it will not be added, and the position of the current class in the list will not change.

Example
a := NewAttributes()
a.AddClass("this")
a.AddClass("that")
a.AddClass("")
fmt.Println(a)
Output:

class="this that"

func (Attributes) AddClassChanged

func (a Attributes) AddClassChanged(v string) bool

AddClassChanged is similar to AddClass, but will return true if the class changed at all.

func (Attributes) AddValues

func (a Attributes) AddValues(attr string, values string) Attributes

AddValues adds space separated values to the end of an attribute value. If a value is not present, the value will be added to the end of the value list. If a value is present, it will not be added, and the position of the current value in the list will not change.

Example
a := Attributes{"abc": "123"}
a.AddValues("abc", "456")
fmt.Println(a.String())
Output:

abc="123 456"

func (Attributes) AddValuesChanged

func (a Attributes) AddValuesChanged(attrKey string, values string) bool

AddValuesChanged adds the given space separated values to the end of the values in the given attribute, removing duplicates and returning true if the attribute was changed at all. An example of a place to use this is the aria-labelledby attribute, which can take multiple space-separated id numbers.

func (Attributes) Class

func (a Attributes) Class() string

Class returns the value of the class attribute.

func (Attributes) Copy

func (a Attributes) Copy() Attributes

Copy returns a copy of the attributes.

func (Attributes) DataAttribute

func (a Attributes) DataAttribute(key string) string

DataAttribute gets the data attribute value that was set previously. The key should be in camelCase.

func (Attributes) Get

func (a Attributes) Get(attr string) string

Get returns the named attribute.

func (Attributes) GetStyle

func (a Attributes) GetStyle(name string) string

GetStyle gives you the value of a single style attribute value. If you want all the attributes as a style string, use StyleString().

func (Attributes) Has

func (a Attributes) Has(attr string) bool

Has returns true if the Attributes has the named attribute.

func (Attributes) HasAttributeValue

func (a Attributes) HasAttributeValue(attr string, value string) bool

HasAttributeValue returns true if the given value exists in the space-separated attribute value.

func (Attributes) HasClass

func (a Attributes) HasClass(c string) bool

HasClass returns true if the given class is in the class list in the class attribute.

Example
a := NewAttributes()
if !a.HasClass("that") {
	fmt.Println("Not found")
}
a.SetClass("this that other")
if a.HasClass("that") {
	fmt.Println("found")
}
Output:

Not found
found

func (Attributes) HasClassWithPrefix added in v1.0.3

func (a Attributes) HasClassWithPrefix(prefix string) bool

HasClassWithPrefix returns true if the attribute has a class with the given prefix.

Example
a := Attributes{"class": "col-2 that"}
found := a.HasClassWithPrefix("col-")
fmt.Println(found)
Output:

true

func (Attributes) HasDataAttribute

func (a Attributes) HasDataAttribute(key string) bool

HasDataAttribute returns true if the data attribute is set. The key should be in camelCase.

func (Attributes) HasStyle

func (a Attributes) HasStyle(name string) bool

HasStyle returns true if the given style is set to any value, and false if not.

Example
a := NewAttributes()
var b []bool
var found bool
found = a.HasStyle("height")
b = append(b, found)
a.SetStyle("height", strconv.Itoa(10))
found = a.HasStyle("height")
b = append(b, found)
fmt.Println(b)
Output:

[false true]

func (Attributes) ID

func (a Attributes) ID() string

ID returns the value of the id attribute.

func (Attributes) IsDisabled

func (a Attributes) IsDisabled() bool

IsDisabled returns true if the "disabled" attribute is set to true.

Example
a := Attributes{"disabled": ""}
fmt.Print(a.IsDisabled())
Output:

true

func (Attributes) IsDisplayed

func (a Attributes) IsDisplayed() bool

IsDisplayed returns true if the "display" attribute is not set, or if it is set, if it is not set to "none".

Example
a := Attributes{"style": "color:blue"}
a.SetDisplay("none")
fmt.Println(a.IsDisplayed())
Output:

false

func (Attributes) Len

func (a Attributes) Len() int

Len returns the number of attributes.

Example
a := Attributes{"id": "45", "class": "aclass"}
fmt.Print(a.Len())
Output:

2

func (Attributes) Merge

func (a Attributes) Merge(aIn Attributes) Attributes

Merge merges the given attributes into the current attributes. Conflicts are generally won by the passed in Attributes. However, styles are merged, so that if both the passed in map and the current map have a styles attribute, the actual style properties will get merged together. Style conflicts are won by the passed in map. The class attribute will merge so that the final classes will be a union of the two.

See Override for a merge that does not merge the styles or classes.

Example
a := NewAttributes().SetClass("this").SetStyle("height", "4em")
b := NewAttributes().Set("class", "that").SetStyle("width", "6")

a = a.Override(b)
fmt.Println(a.SortedString())
Output:

class="that" style="width:6px"

func (Attributes) MergeString

func (a Attributes) MergeString(s string) Attributes

MergeString merges an attribute string into the attributes. Conflicts are won by the string, but styles and classes merge.

It takes an attribute string of the form

a="b" c="d"

func (Attributes) Override

func (a Attributes) Override(overrides Attributes) Attributes

Override will replace attributes with the attributes in overrides. Conflicts are won by the given overrides.

Example
a := NewAttributes().SetClass("this").SetStyle("height", "4em")
b := NewAttributes().Set("class", "that").SetStyle("width", "6")

a = a.Override(b)
fmt.Println(a.SortedString())
Output:

class="that" style="width:6px"

func (Attributes) OverrideString

func (a Attributes) OverrideString(s string) Attributes

OverrideString merges an attribute string into the attributes. Conflicts are won by the string.

It takes an attribute string of the form

a="b" c="d"

func (Attributes) Range

func (a Attributes) Range(f func(key string, value string) bool)

Range will call f for each item in the attributes.

Keys will be ranged over such that repeating the range will produce the same ordering of keys. Return true from the range function to continue iterating, or false to stop.

Example
a := Attributes{"y": "7", "x": "10", "id": "1", "class": "2", "z": "4"}
a.Range(func(k string, v string) bool {
	if k == "z" {
		return false
	}
	fmt.Println(k, "=", v)
	return true
})
Output:

id = 1
class = 2
x = 10
y = 7

func (Attributes) Remove

func (a Attributes) Remove(attr string)

Remove deletes the given attribute.

func (Attributes) RemoveAttribute

func (a Attributes) RemoveAttribute(name string) bool

RemoveAttribute removes the named attribute. Returns true if the attribute existed.

func (Attributes) RemoveClass

func (a Attributes) RemoveClass(v string) bool

RemoveClass removes the named class from the list of classes in the class attribute.

Returns true if the attribute changed.

Example
a := Attributes{"class": "this that"}
changed := a.RemoveClass("this")
fmt.Println(changed)
fmt.Println(a.String())
changed = a.RemoveClass("other")
fmt.Println(changed)
fmt.Println(a.String())
Output:

true
class="that"
false
class="that"

func (Attributes) RemoveClassesWithPrefix

func (a Attributes) RemoveClassesWithPrefix(v string) bool

RemoveClassesWithPrefix removes classes with the given prefix.

Many CSS frameworks use families of classes, which are built up from a base family name. For example, Bootstrap uses 'col-lg-6' to represent a table that is 6 units wide on large screens and Foundation uses 'large-6' to do the same thing. This utility removes classes that start with a particular prefix to remove whatever sizing class was specified. Returns true if the list actually changed.

Example
a := Attributes{"class": "col-2 that"}
a.RemoveClassesWithPrefix("col-")
fmt.Println(a.String())
Output:

class="that"

func (Attributes) RemoveDataAttribute

func (a Attributes) RemoveDataAttribute(key string) bool

RemoveDataAttribute removes the named data attribute. The key should be in camelCase. Returns true if the data attribute existed.

func (Attributes) RemoveStyle

func (a Attributes) RemoveStyle(name string) (changed bool)

RemoveStyle removes the style from the style list. Returns true if there was a change.

Example
a := NewAttributes()
a.SetStyle("height", "10")
a.SetStyle("width", strconv.Itoa(5))
a.RemoveStyle("height")
fmt.Println(a)
Output:

style="width:5px"

func (Attributes) Set

func (a Attributes) Set(name string, v string) Attributes

Set sets a particular attribute and returns Attributes so that it can be chained.

It looks for special attributes like "class", "style" and "data" to do some error checking on them. Use SetData to set data attributes.

Pass v an empty string to create a boolean TRUE attribute, or to FalseValue to set the attribute such that you know it has been set, but will not print in the final html string.

Example

Examples

a := Attributes{}
a = a.Set("class", "a").Set("id", "b")
fmt.Println(a.SortedString())
Output:

id="b" class="a"

func (Attributes) SetChanged

func (a Attributes) SetChanged(name string, v string) (changed bool, err error)

SetChanged sets the value of an attribute and returns changed if something in the attribute structure changed.

It looks for special attributes like "class" and "style" to do some error checking on them. Returns err if the given attribute name or value is not valid.

Use SetDataChanged when setting data attributes for additional validity checks.

func (Attributes) SetClass

func (a Attributes) SetClass(v string) Attributes

SetClass will set the class to the given value, and return the attributes so that you can chain calls.

Example
a := NewAttributes()
a.SetClass("this")
a.SetClass("+ that")
s := a.Class()
fmt.Println(s)
a.SetClass("")
fmt.Println(a.Has("class"))
Output:

this that
false

func (Attributes) SetClassChanged

func (a Attributes) SetClassChanged(value string) bool

SetClassChanged sets the class attribute to the value given.

If you prefix the value with "+ " the given value will be appended to the end of the current class list. If you prefix the value with "- " the given value will be removed from a class list. Otherwise, the current class value is replaced. Returns whether something actually changed or not. value can be multiple classes separated by a space

func (Attributes) SetData

func (a Attributes) SetData(name string, v string) Attributes

SetData sets the given data attribute. Data attribute keys must be in camelCase notation and cannot be hyphenated. The key will get converted to kebab-case for output in html. When referring to the attribute in javascript, javascript will convert it back into camelCase.

Example
a := Attributes{"abc": "123"}
a.SetData("myVal", "456")
fmt.Println(a.SortedString())
Output:

abc="123" data-my-val="456"

func (Attributes) SetDataChanged

func (a Attributes) SetDataChanged(name string, v string) (changed bool, err error)

SetDataChanged sets the given value as an HTML "data-*" attribute. The named value will be retrievable in javascript by using

$obj.dataset.valname;

Note: Data name cases are handled specially. data-* attribute names are supposed to be lower kebab case. Javascript converts dashed notation to camelCase when converting html attributes into object properties. In other words, we give it a camelCase name here, it shows up in the html as a kebab-case name, and then you retrieve it using javascript as camelCase again.

For example, if your html looks like this:

<div id='test1' data-test-case="my test"></div>

You would get that value in javascript by doing:

g$('test1').data('testCase');

Conversion to special html data-* name formatting is handled here automatically. So if you SetData('testCase') here, you can get it using .dataset.testCase in javascript

func (Attributes) SetDisabled

func (a Attributes) SetDisabled(d bool) Attributes

SetDisabled sets the "disabled" attribute to the given value.

Example
a := Attributes{"style": "color:blue"}
a.SetDisabled(true)
fmt.Println(a.SortedString())
a.SetDisabled(false)
fmt.Println(a.SortedString())
Output:

style="color:blue" disabled
style="color:blue"

func (Attributes) SetDisplay

func (a Attributes) SetDisplay(d string) Attributes

SetDisplay sets the "display" attribute to the given value.

Example
a := Attributes{"style": "color:blue"}
a.SetDisplay("none")
fmt.Println(a.SortedString())
Output:

style="color:blue;display:none"

func (Attributes) SetID

func (a Attributes) SetID(i string) Attributes

SetID sets the id attribute to the given value

Example
a := Attributes{}
a = a.SetID("a")
fmt.Println(a.ID())
a = a.SetID("")
fmt.Println(a.Has("id"))
Output:

a
false

func (Attributes) SetIDChanged

func (a Attributes) SetIDChanged(i string) (changed bool, err error)

SetIDChanged sets the id to the given value and returns true if something changed. In other words, if you set the id to the same value that it currently is, it will return false. It will return an error if you attempt to set the id to an illegal value.

func (Attributes) SetStyle

func (a Attributes) SetStyle(name string, v string) Attributes

SetStyle sets the given property in the style attribute

Example
a := NewAttributes()
a.SetStyle("height", "4em")
a.SetStyle("width", "8")
a.SetStyle("width", "- 2")
fmt.Println(a.GetStyle("height"))
fmt.Println(a.GetStyle("width"))
Output:

4em
6px

func (Attributes) SetStyleChanged

func (a Attributes) SetStyleChanged(name string, v string) (changed bool, err error)

SetStyleChanged sets the given style to the given value. If the value is prefixed with a plus, minus, multiply or divide, and then a space, it assumes that a number will follow, and the specified operation will be performed in place on the current value. For example, SetStyle ("height", "* 2") will double the height value without changing the unit specifier. When referring to a value that can be a length, you can use numeric values. In this case, "0" will be passed unchanged, but any other number will automatically get a "px" suffix.

func (Attributes) SetStyles

func (a Attributes) SetStyles(s Style) Attributes

SetStyles merges the given styles with the current styles. The given style wins on collision.

Example
a := Attributes{"style": "color:blue"}
s := Style{"color": "yellow"}
a.SetStyles(s)
fmt.Println(a.String())
Output:

style="color:yellow"

func (Attributes) SetStylesTo

func (a Attributes) SetStylesTo(s string) Attributes

SetStylesTo sets the styles using a traditional css style string with colon and semicolon separators

Example
a := Attributes{"style": "color:blue"}
a.SetStylesTo("color:red")
fmt.Println(a.String())
Output:

style="color:red"

func (Attributes) SortedString

func (a Attributes) SortedString() string

SortedString returns the attributes escaped and encoded, ready to be placed in an HTML tag For consistency, it will use attrSpecialSort to order the keys.

func (Attributes) String

func (a Attributes) String() string

String returns the attributes escaped and encoded, ready to be placed in an HTML tag

func (Attributes) StyleMap

func (a Attributes) StyleMap() Style

StyleMap returns a special Style structure which lets you refer to the styles as a string map.

func (Attributes) StyleString

func (a Attributes) StyleString() string

StyleString returns the css style string, or a blank string if there is none.

func (Attributes) WriteSortedTo

func (a Attributes) WriteSortedTo(w io.Writer) (n int64, err error)

WriteSortedTo writes the attributes escaped, encoded and with sorted keys.

func (Attributes) WriteTo

func (a Attributes) WriteTo(w io.Writer) (n int64, err error)

WriteTo writes the attributes escaped and encoded as fast as possible.

type LabelDrawingMode

type LabelDrawingMode int

The LabelDrawingMode describes how to draw a label when it is drawn. Various CSS frameworks expect it a certain way. Many are not very forgiving when you don't do it the way they expect.

const (
	// LabelDefault means the mode is defined elsewhere, like in a config setting
	LabelDefault LabelDrawingMode = iota
	// LabelBefore indicates the label is in front of the control.
	// Example: <label>MyLabel</label><input ... />
	LabelBefore
	// LabelAfter indicates the label is after the control.
	// Example: <input ... /><label>MyLabel</label>
	LabelAfter
	// LabelWrapBefore indicates the label is before the control's tag, and wraps the control tag.
	// Example: <label>MyLabel<input ... /></label>
	LabelWrapBefore
	// LabelWrapAfter indicates the label is after the control's tag, and wraps the control tag.
	// Example: <label><input ... />MyLabel</label>
	LabelWrapAfter
)

type Style

type Style map[string]string

Style makes it easy to add and manipulate individual properties in a generated style sheet.

Its main use is for generating a style attribute in an HTML tag. It implements the String interface to get the style properties as an HTML embeddable string.

func NewStyle

func NewStyle() Style

NewStyle initializes an empty Style object.

func (Style) Copy added in v1.0.1

func (s Style) Copy() Style

Copy copies the given style. It also turns a map[string]string into a Style.

Example
s := Style{"color": "green", "size": "9"}
s2 := s.Copy()

fmt.Print(s2)
Output:

color:green;size:9

func (Style) Get

func (s Style) Get(property string) string

Get returns the property.

Example
s := NewStyle()
_, _ = s.SetString("height: 9em; width: 100%; position:absolute")
fmt.Print(s.Get("width"))
Output:

100%

func (Style) Has

func (s Style) Has(property string) bool

Has returns true if the given property is in the style.

Example
s := NewStyle()
_, _ = s.SetString("height: 9em; width: 100%; position:absolute")
fmt.Print(s.Has("width"), s.Has("display"))
Output:

true false

func (Style) Len

func (s Style) Len() int

Len returns the number of properties in the style.

Example
s := Style{"color": "green", "size": "9"}
fmt.Print(s.Len())
Output:

2

func (Style) Merge

func (s Style) Merge(m Style)

Merge merges the styles from one style to another. Conflicts will overwrite the current style.

func (Style) Remove

func (s Style) Remove(property string)

Remove removes the property.

Example
s := NewStyle()
_, _ = s.SetString("height: 9em; width: 100%; position:absolute")
s.Remove("position")
fmt.Print(s)
Output:

height:9em;width:100%

func (Style) RemoveAll

func (s Style) RemoveAll()

RemoveAll resets the style to contain no styles

Example
s := NewStyle()
_, _ = s.SetString("height: 9em; width: 100%; position:absolute")
s.RemoveAll()
fmt.Print(s)
Output:

func (Style) Set

func (s Style) Set(property string, value string) Style

Set is like SetChanged, but returns the Style for chaining.

Example (A)
s := NewStyle()
s.Set("height", "9")
fmt.Print(s)
Output:

height:9px
Example (B)
s := NewStyle()
_, _ = s.SetString("height:9px")
s.Set("height", "+ 10")
fmt.Print(s)
Output:

height:19px

func (Style) SetChanged

func (s Style) SetChanged(property string, value string) (changed bool, err error)

SetChanged sets the given property to the given value.

If the value is prefixed with a plus, minus, multiply or divide, and then a space, it assumes that a number will follow, and the specified operation will be performed in place on the current value For example, Set ("height", "* 2") will double the height value without changing the unit specifier When referring to a value that can be a length, you can use numeric values. In this case, "0" will be passed unchanged, but any other number will automatically get a "px" suffix.

func (Style) SetString

func (s Style) SetString(text string) (changed bool, err error)

SetString receives a style encoded "style" attribute into the Style structure (e.g. "width: 4px; border: 1px solid black")

Example
s := NewStyle()
_, _ = s.SetString("height: 9em; width: 100%; position:absolute")
fmt.Print(s)
Output:

height:9em;position:absolute;width:100%

func (Style) String

func (s Style) String() string

String returns the string version of the style attribute, suitable for inclusion in an HTML style tag

type TagBuilder

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

A TagBuilder creates a tag using a builder pattern, starting out with the tag name and slowly adding parts to it, describing it, until you are ready to print out the entire html tag. The zero value is usable.

func NewTagBuilder

func NewTagBuilder() *TagBuilder

NewTagBuilder starts a tag build, though you can use a tag builder from its zero value too.

func (*TagBuilder) Class

func (b *TagBuilder) Class(class string) *TagBuilder

Class sets the class attribute to the value given. If you prefix the value with "+ " the given value will be appended to the end of the current class list. If you prefix the value with "- " the given value will be removed from the class list. Otherwise, the current class value is replaced. The given class can be multiple classes separated by a space.

Example
fmt.Println(NewTagBuilder().Tag("div").Class("bob sam"))
Output:

<div class="bob sam"></div>

func (*TagBuilder) ID

func (b *TagBuilder) ID(id string) *TagBuilder

ID sets the id attribute

Example
fmt.Println(NewTagBuilder().Tag("div").ID("bob"))
Output:

<div id="bob"></div>

func (*TagBuilder) InnerHtml

func (b *TagBuilder) InnerHtml(html string) *TagBuilder

InnerHtml sets the inner html of the tag.

Remember this is HTML, and will not be escaped.

Example
fmt.Println(NewTagBuilder().Tag("div").InnerHtml("<p>A big deal</p>"))
Output:

<div>
<p>A big deal</p>
</div>

func (*TagBuilder) InnerText

func (b *TagBuilder) InnerText(text string) *TagBuilder

InnerText sets the inner part of the tag to the given text. The text will be escaped.

Example
fmt.Println(NewTagBuilder().Tag("div").InnerText("<p>A big deal</p>"))
Output:

<div>
&lt;p&gt;A big deal&lt;/p&gt;
</div>

func (*TagBuilder) IsVoid

func (b *TagBuilder) IsVoid() *TagBuilder

IsVoid will make the builder output a void tag instead of one with inner html.

Example
fmt.Println(NewTagBuilder().Tag("img").IsVoid())
Output:

<img>
func (b *TagBuilder) Link(href string) *TagBuilder

Link is a shortcut that will set the tag to "a" and the "href" to the given destination. This is not the same as an actual "link" tag, which points to resources from the header.

func (*TagBuilder) Set

func (b *TagBuilder) Set(attribute string, value string) *TagBuilder

Set sets the attribute to the given value

Example
fmt.Println(NewTagBuilder().Tag("div").Set("me", "you"))
Output:

<div me="you"></div>

func (*TagBuilder) String

func (b *TagBuilder) String() string

String ends the builder and returns the html.

Example
s := NewTagBuilder().Tag("div").InnerHtml("<p>A big deal</p>").String()
fmt.Println(s)
Output:

<div>
<p>A big deal</p>
</div>

func (*TagBuilder) Tag

func (b *TagBuilder) Tag(tag string) *TagBuilder

Tag sets the tag value

Example
fmt.Println(NewTagBuilder().Tag("div"))
Output:

<div></div>

type VoidTag

type VoidTag struct {
	Tag  string
	Attr Attributes
}

VoidTag represents a void tag, which is a tag that does not need a matching closing tag.

func (VoidTag) Render

func (t VoidTag) Render() string

Render returns the rendered version of the tag.

Example
v := VoidTag{"br", Attributes{"id": "hi"}}
fmt.Println(v.Render())
Output:

<br id="hi">

Jump to

Keyboard shortcuts

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