动态解析文件

huangapple go评论112阅读模式
英文:

Dynamically parsing files

问题

var templates = template.Must(template.ParseFiles(
"index.html", // 主文件
"subfolder/index.html", // 子文件夹中的同名文件会在运行时出错
"includes/header.html", "includes/footer.html",
))

func main() {
// 遍历并解析文件
filepath.Walk("files", func(path string, info os.FileInfo, err error) {
if !info.IsDir() {
// 将路径添加到ParseFiles中

  1. }
  2. return
  3. })
  4. http.HandleFunc("/", home)
  5. http.ListenAndServe(":8080", nil)

}

func home(w http.ResponseWriter, r *http.Request) {
render(w, "index.html")
}

func render(w http.ResponseWriter, tmpl string) {
err := templates.ExecuteTemplate(w, tmpl, nil)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}

英文:

For parsing files i have setup a variable for template.ParseFiles and i currently have to manually set each file.

Two things:

How would i be able to walk through a main folder and a multitude of subfolders and automatically add them to ParseFiles so i dont have to manually add each file individually?

How would i be able to call a file with the same name in a subfolder because currently I get an error at runtime if i add same name file in ParseFiles.

<!-- language: lang-go -->

  1. var templates = template.Must(template.ParseFiles(
  2. &quot;index.html&quot;, // main file
  3. &quot;subfolder/index.html&quot; // subfolder with same filename errors on runtime
  4. &quot;includes/header.html&quot;, &quot;includes/footer.html&quot;,
  5. ))
  6. func main() {
  7. // Walk and ParseFiles
  8. filepath.Walk(&quot;files&quot;, func(path string, info os.FileInfo, err error) {
  9. if !info.IsDir() {
  10. // Add path to ParseFiles
  11. }
  12. return
  13. })
  14. http.HandleFunc(&quot;/&quot;, home)
  15. http.ListenAndServe(&quot;:8080&quot;, nil)
  16. }
  17. func home(w http.ResponseWriter, r *http.Request) {
  18. render(w, &quot;index.html&quot;)
  19. }
  20. func render(w http.ResponseWriter, tmpl string) {
  21. err := templates.ExecuteTemplate(w, tmpl, nil)
  22. if err != nil {
  23. http.Error(w, err.Error(), http.StatusInternalServerError)
  24. }
  25. }

答案1

得分: 4

要遍历一个目录查找文件,请参阅:http://golang.org/pkg/path/filepath/#Walk 或者 http://golang.org/pkg/html/template/#Newhttp://golang.org/pkg/html/template/#Template.Parse

至于你的另一个问题,ParseFiles 使用文件的基本名称作为模板名称,这导致模板发生冲突。你有两个选择:

  1. 重命名文件。
  2. 使用 t := template.New("你选择的名称") 创建一个初始模板
    1. 使用你已经开始的遍历函数,并为每个模板文件调用 t.Parse("文件中的文本")。你需要自己打开并读取模板文件的内容来传递给这里。

编辑:代码示例。

  1. func main() {
  2. // 遍历和解析文件
  3. t = template.New("我的模板名称")
  4. filepath.Walk("files", func(path string, info os.FileInfo, err error) {
  5. if !info.IsDir() {
  6. // 将路径添加到 ParseFiles
  7. content := ""
  8. // 在这里将文件读取到 content 中
  9. t.Parse(content)
  10. }
  11. return
  12. })
  13. http.HandleFunc("/", home)
  14. http.ListenAndServe(":8080", nil)
  15. }
英文:

To walk a directory looking for files see: http://golang.org/pkg/path/filepath/#Walk or http://golang.org/pkg/html/template/#New and http://golang.org/pkg/html/template/#Template.Parse

As for your other question ParseFiles uses the base name of the file as the template name which results in a collision in your template. You have two choices

  1. Rename the file.
  2. use t := template.New(&quot;name of your choice&quot;) to create an initial template
  3. Use the walk function you already have started and call t.Parse(&quot;text from file&quot;) for each template file. You'll have to open and read the contents of the template files yourself to pass in here.

Edit: Code example.

  1. func main() {
  2. // Walk and ParseFiles
  3. t = template.New(&quot;my template name&quot;)
  4. filepath.Walk(&quot;files&quot;, func(path string, info os.FileInfo, err error) {
  5. if !info.IsDir() {
  6. // Add path to ParseFiles
  7. content := &quot;&quot;
  8. // read the file into content here
  9. t.Parse(content)
  10. }
  11. return
  12. })
  13. http.HandleFunc(&quot;/&quot;, home)
  14. http.ListenAndServe(&quot;:8080&quot;, nil)
  15. }

答案2

得分: 0

所以基本上我设置了New("我想要的路径名").Parse("从读取文件得到的字符串"),同时遍历文件夹。

var templates = template.New("temp")

func main() {
// 遍历并解析文件
parseFiles()

  1. http.HandleFunc("/", home)
  2. http.ListenAndServe(":8080", nil)

}

////////////////////////
// 处理函数 //
////////////////////////
func home(w http.ResponseWriter, r *http.Request) {
render(w, "index.html")
render(w, "subfolder/index.html")
}

//////////////////////////
// 可重用的函数 //
//////////////////////////
func parseFiles() {
filepath.Walk("files", func(path string, info os.FileInfo, err error) error {
if !info.IsDir() {
filetext, err := ioutil.ReadFile(path)
if err != nil {
return err
}
text := string(filetext)
templates.New(path).Parse(text)
}
return nil
})
}

func render(w http.ResponseWriter, tmpl string) {
err := templates.ExecuteTemplate(w, tmpl, nil)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}

英文:

So basically i set New("path name i want").Parse("String from read file") while walking through the folders.

<!-- language: lang-go -->

  1. var templates = template.New(&quot;temp&quot;)
  2. func main() {
  3. // Walk and ParseFiles
  4. parseFiles()
  5. http.HandleFunc(&quot;/&quot;, home)
  6. http.ListenAndServe(&quot;:8080&quot;, nil)
  7. }
  8. //////////////////////
  9. // Handle Functions //
  10. //////////////////////
  11. func home(w http.ResponseWriter, r *http.Request) {
  12. render(w, &quot;index.html&quot;)
  13. render(w, &quot;subfolder/index.html&quot;)
  14. }
  15. ////////////////////////
  16. // Reusable functions //
  17. ////////////////////////
  18. func parseFiles() {
  19. filepath.Walk(&quot;files&quot;, func(path string, info os.FileInfo, err error) error {
  20. if !info.IsDir() {
  21. filetext, err := ioutil.ReadFile(path)
  22. if err != nil {
  23. return err
  24. }
  25. text := string(filetext)
  26. templates.New(path).Parse(text)
  27. }
  28. return nil
  29. })
  30. }
  31. func render(w http.ResponseWriter, tmpl string) {
  32. err := templates.ExecuteTemplate(w, tmpl, nil)
  33. if err != nil {
  34. http.Error(w, err.Error(), http.StatusInternalServerError)
  35. }
  36. }

huangapple
  • 本文由 发表于 2012年10月10日 02:48:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/12806474.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定