tsawler / bookings-app

The repository for Building Modern Web Applications with Go.
https://www.udemy.com/course/building-modern-web-applications-with-go/?referralCode=0415FB906223F10C6800
57 stars 34 forks source link

Render templates #1

Open khanzadimahdi opened 3 years ago

khanzadimahdi commented 3 years ago

Hi, recently I have seen your Golang tutorial. that's great.

I recommend rendering templates like the below:

func parseTemplate() (map[string]*template.Template, error) {
    templates := map[string]*template.Template{}

    layouts, err := filepath.Glob(fmt.Sprintf("%s/*%s", pathToTemplates, layoutSuffix))
    if err != nil {
        return templates, err
    }

    pages, err := filepath.Glob(fmt.Sprintf("%s/*%s", pathToTemplates, pageSuffix))
    if err != nil {
        return templates, err
    }

    for _, page := range pages {
        name := filepath.Base(page)

        filenames := make([]string, 0, len(layouts)+1)

        filenames = append(filenames, page)
        filenames = append(filenames, layouts...)

        t, err := template.New(name).ParseFiles(filenames...)
        if err != nil {
            return templates, err
        }

        templates[name] = t
    }

    return templates, nil
}

as you see, we don't need to double render templates! we find our page and render it with all layouts at once.

in the tutorial, we render the given page and then we render it with layouts!!!! I think we don't need the second step.