Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support html/template #16

Open
xeoncross opened this issue Feb 1, 2018 · 2 comments
Open

Support html/template #16

xeoncross opened this issue Feb 1, 2018 · 2 comments

Comments

@xeoncross
Copy link

xeoncross commented Feb 1, 2018

It looks like there is no option for returning HTML/templates.

Can we add a check for this?

type IndexHandler struct{}

func (m *IndexHandler) Handle(c *gongular.Context) (err error) {
	var indexHTML = `<h1>Hello World</h1>`
	var tmpl *template.Template
	tmpl, err = template.New("index").Parse(indexHTML)
	c.SetBody(tmpl)
	return
}

The work around is to manually set the header and return []byte.

c.Header("Content-Type", "text/html")
c.SetBody([]byte(indexHTML))

Possible Solution:

if v, ok := a.(*template.Template); ok {
	c.w.WriteHeader(c.status)
	err := v.Execute(c.w)
	if err != nil {
		c.logger.Println("Could not write the response", err)
	}
	return 1 // todo?
}
@xeoncross xeoncross changed the title How do you send HTML? Support html/template Feb 1, 2018
@mustafaakin
Copy link
Owner

Not having used templates myself, I did not even think about it. Do you have anything to propose? Are templates cached? If we add a field as *template.Template to handler, or left it to user? Templates can be passed with dependency injections.

For plain HTML, I can implement:

c.SetHtml(..)

as a shortcut for:

c.Header("Content-Type", "text/html")
c.SetBody([]byte(indexHTML))

@xeoncross
Copy link
Author

xeoncross commented Mar 2, 2018

Well, the nice thing would be for the system to handle *template.Template for you. Since Templates almost always need params, having a SetHtml() seems wasteful as you would 1) have to manually load and compile templates in each handler (compare with automatic JSON responses) and 2) you would end up passing large byte streams/slices around multiple times causing wasted GC and allocs.

My prosed type-check solution up above assumes the templates have no params from the handler/context which isn't normal:

tmpl, err := template.New("name").Parse(`Name: {{.Name}}`)
err = tmpl.Execute(c.w, struct{Name string}{Name: "John"})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants