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

How can I use html template? #27

Closed
dorajistyle opened this issue Jul 3, 2014 · 8 comments
Closed

How can I use html template? #27

dorajistyle opened this issue Jul 3, 2014 · 8 comments
Assignees
Labels

Comments

@dorajistyle
Copy link

Hello.
Thank you for sharing nice framework.

I wonder how can I use html template in gin framework.

I've tried below,

html := template.ParseFiles("file1", "file2")
r.HTMLTemplates = html

Then I've got an error bellow.

multiple-value "html/template".ParseFiles() in single-value context

And I've researched bit more.
Finally discovered Context.HTML.

func render(c *gin.Context) {
    c.HTML(200, "template/index.html", gin.H{})
}

but it gave me a blank page.

How can I use html template?

@pinscript
Copy link
Contributor

Hi,

Look at the example in the README[0], that should work.

The error, "multiple valie {..} in single-value context", is because template.ParseFiles returns multiple values, a pointer to a template and an error. The right usage would be:

tmpl, err := template.ParseFiles("file1", "file2")

Edit: I saw that the second example in the README is wrong. Fixing.

[0] https://github.com/gin-gonic/gin/blob/master/README.md#html-rendering

@dorajistyle
Copy link
Author

Hi @alexandernyquist

Thanks for the quick response.

I modifed the code and it runs without errors.
But I can't see the template on web.
What should I do more?

Regards,

@pinscript
Copy link
Contributor

I've created a simple gist[0] which works for me. Can you please try it out?

[0] https://gist.github.com/alexandernyquist/e7e9a00ff2ab40a9252a

@dorajistyle
Copy link
Author

Thanks for the example.

But it gave me same result. (blank page)

I've got templates from https://github.com/jadekler/git-go-websiteskeleton

type Data struct {
Name string
}

func main() {
html,err := template.ParseFiles("templates/home/home.html", "templates/layout.html")
r.HTMLTemplates = html
if err != nil {
var stack [4096]byte
runtime.Stack(stack[:], false)
log.Printf("%q\n%s\n", err, stack[:])

}

//r.LoadHTMLTemplates("frontend/static/templates/*")

r.GET("/test", func(c *gin.Context){
    //c.String(200, "pang pong porobong")
    c.HTML(200, "home.html", Data{"@dorijastyle"})
    //frontend.GetHomePage(c)
})

}

@pinscript
Copy link
Contributor

I added a new (simplified from git-go-websiteskeleton) example[0]. The key is to not include all templates outside the routes since that will cause redeclaration issues.

We should probably hare a more convenient way of doing this. Maybe a engine.LoadHTMLTemplateFiles(files...string) and engine.LoadHTMLTemplateGlob(pattern string)? That way, the user does not need to import html/template. Of course, shorter names would be nice ;)

[0] https://gist.github.com/alexandernyquist/1ee331db9f5bf0d577d6

@dorajistyle
Copy link
Author

Hi Alexander,
Thanks for the kind response.

I've tried it again, and it failed.
And I've got a panic but Golang didn't catched it. :(
Whole source correct logically.
I was confused because I'm a newbie of Golang.

So I 've tried a job in software bible.
"When software not work, delete it and install it again."

It works perfectly. :D

Thanks a lot!

@manucorporat
Copy link
Contributor

I liked the idea of including two easy ways to load the templates, using glob and a list of files.

@sdvdxl
Copy link

sdvdxl commented Aug 22, 2015

I just write a finder to find templates,

func TemplatesFinder(engine *gin.Engine, pathOfRoot, templateDirName string) {
    dir := gin.Dir(pathOfRoot, true)
    file, err := dir.Open(templateDirName)
    util.PanicError(err)
    defer file.Close()
    dirs, err := file.Readdir(10)
    util.PanicError(err)

    templatePages := make([]string, 0, 10)
    dirStack := collections.NewStack(10)
    for _, v := range dirs {
        if v.IsDir() {
            fileNode := v.Name()
            dirStack.Push(fileNode)
        } else {
            templatePages = append(templatePages, templateDirName + "/" + v.Name())
        }
    }

    // range every dir, and find sub dirs
    for {
        if rootDir, ok := dirStack.Pop(); ok {
            tmpDir := fmt.Sprint(rootDir)

            dir := gin.Dir(templateDirName + "/" + tmpDir, true)
            file, err := dir.Open(".")
            util.PanicError(err)
            defer file.Close()
            dirs, err = file.Readdir(10)
            for _, v := range dirs {
                path := tmpDir + "/" + v.Name()
                if v.IsDir() {
                    dirStack.Push(tmpDir)
                } else {
                    templatePages = append(templatePages, templateDirName + "/" + path)
                }
            }
        } else {
            log.Logger.Debug("has no elements....")
            break
        }
    }

    temp, err := template.ParseGlob("templates/*\\.tmpl")
    util.PanicError(err)

    for _, v := range temp.Templates() {
        log.Logger.Debug("templates: %v", v.Name())
    }

    log.Logger.Debug("all template pages: %v", templatePages)
    engine.LoadHTMLFiles(templatePages...)
}

and u can use like this just assume your templates are in templates directory, and main file is in the root of project:

g = gin.New()
TemplatesFinder(g, ".", "templates")

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

No branches or pull requests

5 participants