为解析的模板指定名称

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

Specify names for parsed templates

问题

我正在尝试使用文件夹中的walk动态解析文件,并且我希望能够设置文件的路径"path/file.html"。但是我的问题是,如果我在文件夹"path/folder/files.html"中有一个文件,我无法这样做,因为当我执行ExecuteTemplate时,文件名将是相同的"files.html"。是否可以在ParseFiles时为每个模板命名?

如果一次尝试处理所有文件无法工作,我可以一个一个地处理文件。

// 解析文件并发送到responsewriter
func View(w http.ResponseWriter, path string) {
temp, err := template.ParseFiles("application/views/" + path + ".html")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
} else {
temp.ExecuteTemplate(w, path, nil)
}
}

英文:

I am trying to dynamically parse files using walk in a folder and I want to be able to set the path of the file "path/file.html". But my issue is if I have a file in a folder "path/folder/files.html" I can't do it because when I ExecuteTemplate the file name will be the same "files.html". Is it possible to name each template as I ParseFiles?

Im ok with doing a file one at a time if trying to do them all at once wont work.

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

// Parse file and send to responsewriter
func View(w http.ResponseWriter, path string) {
	temp, err := template.ParseFiles(&quot;application/views/&quot;+path+&quot;.html&quot;)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	} else {
		temp.ExecuteTemplate(w, path, nil)
	}
}

答案1

得分: 3

使用filepath.Walk和一个consumer方法遍历文件系统,该方法将使用完整的文件路径作为模板名称创建模板:

package main

import (
    "fmt"
    "html/template"
    "os"
    "path/filepath"
)

func consumer(p string, i os.FileInfo, e error) error {
    t := template.New(p)
    fmt.Println(t.Name())
    return nil
}

func main() {
    filepath.Walk("/path/to/template/root", filepath.WalkFunc(consumer))
}
英文:

Walk the filesystem using filepath.Walk and a consumer method that will create templates with the full file paths as names:

package main

import (
	&quot;fmt&quot;
	&quot;html/template&quot;
	&quot;os&quot;
	&quot;path/filepath&quot;
)

func consumer(p string, i os.FileInfo, e error) error {
	t := template.New(p)
	fmt.Println(t.Name())
	return nil
}

func main() {
	filepath.Walk(&quot;/path/to/template/root&quot;, filepath.WalkFunc(consumer))
}

答案2

得分: 0

你可以尝试使用template.Lookup,整个过程如下:

var (
   templates *template.Template	
)

func loadTemplate() {
    funcMap := template.FuncMap{		
	    "safe": func(s string) template.HTML {
		    return template.HTML(s)
	    },
    }
    var err error
    templates, err = utils.BuildTemplate("/theme/path/", funcMap)
    if err != nil {
  	    log.Printf("无法读取模板文件 %v,", err)
    }	
 }
func homeHandler(w http.ResponseWriter, r *http.Request) {	
        //查找你想要使用的主题
    templ = templates.Lookup("theme.html")
    err := templ.Execute(w, data)
    if err != nil {
	    log.Println(err)
    }
 }

 func main() {
   loadTemplate()
 }

BuildTemplate的样子如下:

func BuildTemplate(dir string, funcMap template.FuncMap) (*template.Template, error) {
	fs, err := ioutil.ReadDir(dir)
	if err != nil {
		fmt.Printf("无法读取模板文件夹:%s\n", dir)
		return nil, err
	}
	files := make([]string, len(fs))
	for i, f := range (fs) {
		files[i] = path.Join(dir, f.Name())
	}
	return template.Must(template.New("Template").Funcs(funcMap).ParseFiles(files...)), nil
}
英文:

You can try template.Lookup, the whole process looks like:

var (
   templates *template.Template	
)

func loadTemplate() {
    funcMap := template.FuncMap{		
	    &quot;safe&quot;:func(s string) template.HTML {
		    return template.HTML(s)
	    },
    }
    var err error
    templates, err = utils.BuildTemplate(&quot;/theme/path/&quot;, funcMap)
    if err != nil {
  	    log.Printf(&quot;Can&#39;t read template file %v,&quot;, err)
    }	
 }
func homeHandler(w http.ResponseWriter, r *http.Request) {	
        //lookup the theme your want to use
    templ = templates.Lookup(&quot;theme.html&quot;)
    err := templ.Execute(w, data)
    if err != nil {
	    log.Println(err)
    }
 }

 func main() {
   loadTemplate()
 }

BuildTemplate looks like:

func BuildTemplate(dir string, funcMap template.FuncMap) (*template.Template, error) {
	fs, err := ioutil.ReadDir(dir)
	if err != nil {
		fmt.Printf(&quot;Can&#39;t read template folder: %s\n&quot;, dir)
		return nil, err
	}
	files := make([]string, len(fs))
	for i, f := range (fs) {
		files[i] = path.Join(dir, f.Name())
	}
	return template.Must(template.New(&quot;Template&quot;).Funcs(funcMap).ParseFiles(files...)), nil
}

huangapple
  • 本文由 发表于 2012年9月15日 03:32:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/12430870.html
匿名

发表评论

匿名网友

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

确定