Giter VIP home page Giter VIP logo

Comments (8)

sdvdxl avatar sdvdxl commented on March 29, 2024 3

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")

from gin.

manucorporat avatar manucorporat commented on March 29, 2024 1

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

from gin.

pinscript avatar pinscript commented on March 29, 2024

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

from gin.

dorajistyle avatar dorajistyle commented on March 29, 2024

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,

from gin.

pinscript avatar pinscript commented on March 29, 2024

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

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

from gin.

dorajistyle avatar dorajistyle commented on March 29, 2024

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)
})

}

from gin.

pinscript avatar pinscript commented on March 29, 2024

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

from gin.

dorajistyle avatar dorajistyle commented on March 29, 2024

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!

from gin.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.