go - 指定已解析模板的名称

标签 go go-templates

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

如果尝试一次完成所有文件行不通,我可以一次处理一个文件。

// Parse file and send to 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)
    }
}

最佳答案

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

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

关于go - 指定已解析模板的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12430870/

相关文章:

algorithm - 递归算法中的 Go channel 导致重复值

go - 为什么我的 map 合并功能会合并所有内容?

go - 单元测试 hyperledger fabric 链码 (GetPrivateData)

json - 如何跳过 JSON 对象流中的 'noise'?

go - 在1页中将相同的模板与不同的参数/变量一起使用

golang 不能在 sort.Sort 的参数中使用类型作为类型 sort.Interface

go - 如何在子目录中加载模板

html - 使用 HTML 表单部分显示图像文件的简单方法

go-templates - 比较模板中的字符串

string - 文本/模板如何确定 map 的 "default textual representation"?