动态解析文件

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

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中

    }
    return
})

http.HandleFunc("/", home)
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 -->

var templates = template.Must(template.ParseFiles(
	&quot;index.html&quot;, // main file
    &quot;subfolder/index.html&quot; // subfolder with same filename errors on runtime
	&quot;includes/header.html&quot;, &quot;includes/footer.html&quot;,
))


func main() {
    // Walk and ParseFiles
    filepath.Walk(&quot;files&quot;, func(path string, info os.FileInfo, err error) {
        if !info.IsDir() {
            // Add path to ParseFiles


        }
        return
    })

    http.HandleFunc(&quot;/&quot;, home)
    http.ListenAndServe(&quot;:8080&quot;, nil)
}

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

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

答案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("文件中的文本")。你需要自己打开并读取模板文件的内容来传递给这里。

编辑:代码示例。

func main() {
    // 遍历和解析文件
    t = template.New("我的模板名称")
    filepath.Walk("files", func(path string, info os.FileInfo, err error) {
        if !info.IsDir() {
            // 将路径添加到 ParseFiles
            content := ""
            // 在这里将文件读取到 content 中
            t.Parse(content)
        }
        return
    })

    http.HandleFunc("/", home)
    http.ListenAndServe(":8080", nil)
}
英文:

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.

func main() {
    // Walk and ParseFiles
    t = template.New(&quot;my template name&quot;)
    filepath.Walk(&quot;files&quot;, func(path string, info os.FileInfo, err error) {
        if !info.IsDir() {
            // Add path to ParseFiles
            content := &quot;&quot;
            // read the file into content here
            t.Parse(content)
        }
        return
    })

    http.HandleFunc(&quot;/&quot;, home)
    http.ListenAndServe(&quot;:8080&quot;, nil)
}

答案2

得分: 0

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

var templates = template.New("temp")

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

http.HandleFunc("/", home)
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 -->

var templates = template.New(&quot;temp&quot;)

func main() {
    // Walk and ParseFiles
    parseFiles()

    http.HandleFunc(&quot;/&quot;, home)
    http.ListenAndServe(&quot;:8080&quot;, nil)
}

//////////////////////
// Handle Functions //
//////////////////////
func home(w http.ResponseWriter, r *http.Request) {
	render(w, &quot;index.html&quot;)
    render(w, &quot;subfolder/index.html&quot;)
}

////////////////////////
// Reusable functions //
////////////////////////
func parseFiles() {
	filepath.Walk(&quot;files&quot;, 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)
	}
}

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:

确定