Comments (8)
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.
I liked the idea of including two easy ways to load the templates, using glob and a list of files.
from gin.
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.
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.
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.
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.
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.
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)
- Will it be made into a more comprehensive framework later on? HOT 4
- How does the gin close the log file? HOT 3
- Should we use url.PathUnescape instead of url.QueryUnescape when UnescapePathValues is true
- go get failed: The requested name is valid, but no data of the requested type was found HOT 1
- Attach Response Headers (or middlewares) to redirected requests (CORS issues) HOT 1
- Should context.GetRawData() also copy body to BodyBytesKey? HOT 3
- YAML BindBody should not parse JSON content HOT 1
- Gin do not support javascript ? HOT 5
- Does gin.Recovery() run before or after Group middleware? HOT 1
- How can i prevent a http connection to close HOT 3
- BasicAuth is not suitable for proxy auth
- Can't get status as expected from context.Status() HOT 1
- Gin Context implementation breaks context.Context contract HOT 3
- [Suggestions] Introducing an AI-powered robot to assist with daily issue and pull request (PR) tasks.
- Need c.JSON() response like behaviour for c.SSEvent() response for supporting first party clients like OpenAI SDK HOT 2
- custom time.Time type can not use bindQuery get a value. HOT 2
- configure server parameters HOT 1
- The binding:"required" tag does not seem to work for struct types HOT 3
- Is there a way to preserve order in JSON on response? HOT 1
- redirect is not success HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from gin.