// New creates the HTML for a select menu instance with the specified parameters. func New(options []string, defaultOption string, query url.Values, queryParameter string) template.HTML { selectElement := &html.Node{Type: html.ElementNode, Data: "select"} var selectedOption = defaultOption if query.Get(queryParameter) != "" { selectedOption = query.Get(queryParameter) } if !contains(options, selectedOption) { options = append(options, selectedOption) } for _, option := range options { o := &html.Node{Type: html.ElementNode, Data: "option"} o.AppendChild(htmlg.Text(option)) if option == selectedOption { o.Attr = append(o.Attr, html.Attribute{Key: "selected"}) } selectElement.AppendChild(o) } selectElement.Attr = append(selectElement.Attr, html.Attribute{ Key: "oninput", // HACK: Don't use Sprintf, properly encode (as json at this time). Val: fmt.Sprintf(`SelectMenuOnInput(event, this, %q, %q);`, strconv.Quote(defaultOption), strconv.Quote(queryParameter)), }) return htmlg.Render(selectElement) }
func Example() { // Context-aware escaping is done just like in html/template. html := htmlg.Render( htmlg.Text("Hi & how are you, "), htmlg.A("Gophers", "https://golang.org/"), htmlg.Text("? <script> is a cool gopher."), ) fmt.Fprintln(os.Stdout, html) // Output: // Hi & how are you, <a href="https://golang.org/">Gophers</a>? <script> is a cool gopher. }
// New creates the HTML for a checkbox instance. Its checked value is directly connected // to the presence of queryParameter. // Changing either the presence of queryParameter, or checking/unchecking the checkbox // will result in the other updating to match. func New(defaultValue bool, query url.Values, queryParameter string) template.HTML { inputElement := &html.Node{ Type: html.ElementNode, Data: "input", Attr: []html.Attribute{{Key: "type", Val: "checkbox"}}, } var selectedValue = defaultValue if _, set := query[queryParameter]; set { selectedValue = !selectedValue } if selectedValue { inputElement.Attr = append(inputElement.Attr, html.Attribute{Key: "checked"}) } inputElement.Attr = append(inputElement.Attr, html.Attribute{ Key: "onchange", // HACK: Don't use Sprintf, properly encode (as json at this time). Val: fmt.Sprintf(`CheckboxOnChange(event, this, %v, %q);`, defaultValue, strconv.Quote(queryParameter)), }) return htmlg.Render(inputElement) }