I don’t know if this will be helpful to you or not, but I’ve made a package 
that is basically a copy/paste of the autoescaping logic from html/template, 
but modified to work at runtime instead of when compiling a template: 
github.com/andybalholm/escaper <http://github.com/andybalholm/escaper>

It lets you write your “template” logic in plain Go instead of the special 
template language, without needing to spend a lot of extra effort on escaping. 
The runtime impact would be mixed: you would lose the overhead of reflection, 
but gain the overhead of figuring out HTML contexts at runtime. I don’t know if 
it would be a net performance gain or not.

Anyway, your RenderComponent method would look something like this:

func (b *ButtonRenderer) RenderComponent(wr io.Writer, view 
mgc.ViewComponentRenderer, args ...interface{}) (string, error) {
        if button, ok := view.(*components.Button); !ok {
                return "", errors.New("wrong type expected components.Button")
        } else {
                e := escaper.New(w)

                tag := "button"
                if button.Attr.Has("href") {
                        if button.Attr.Has("disabled") {
                                tag = "span"
                        } else {
                                tag = "a"
                        }
                }

                e.Literal("<"+tag+" ")

                for _, v := range button.Attr {
                        e.Print(v.Name+"='", v.Value, "' ")
                }

                e.Print("class='", button.Classes.Render(), "' ")

                if button.GetValue() != "" {
                        e.Print("value='", button.GetValue(), "'")
                }

                e.Print(">", button.GetLabel(),  "</"+tag+">")
        }
        return "", nil
}

The only real thinking about escaping you need to do is deciding whether to use 
a plus or a comma between strings you want to join, to preserve the proper 
alternation between literals and values in the arguments to e.Print.

Andy

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to