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

Pre-built Template Function #2673

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open

Conversation

IsusRamzy
Copy link

I have added a pre-built templates function to render HTML easily.

@IsusRamzy
Copy link
Author

Hello!

@IsusRamzy IsusRamzy changed the title Update echo.go Pre-built Template Function Aug 15, 2024
@IsusRamzy
Copy link
Author

Can you please merge?

@IsusRamzy
Copy link
Author

Hi!

Copy link
Contributor

@aldas aldas left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This code does not compile. Please fit it before I even review it.

Copy link
Contributor

@aldas aldas left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nb: fix compilation errors

}

func BeginTemplates(e *Echo) {
templates := template.Must(template.ParseGlob("templates/*.html"))
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • instead of Must (which panics) use functions that return errors and that function should return an error
  • instead of hardcoded "templates/*.html" pass it as function parameter

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This code can be shortened to

// import 
// 	htmlTmpl "html/template"
// 	textTmpl "text/template"

type TextTemplateRenderer struct {
	Templates *textTmpl.Template
}

func (t *TextTemplateRenderer) Render(w io.Writer, name string, data interface{}, c Context) error {
	return t.Templates.ExecuteTemplate(w, name, data)
}

type HTMLTemplateRenderer struct {
	Templates *htmlTmpl.Template
}

func (t *HTMLTemplateRenderer) Render(w io.Writer, name string, data interface{}, c Context) error {
	return t.Templates.ExecuteTemplate(w, name, data)
}

and use as

	e.Renderer = &echo.HTMLTemplateRenderer{
		Templates: template.Must(template.ParseGlob("templates/*.html")),
	}

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

Successfully merging this pull request may close these issues.

2 participants