程序问答   发布时间:2022-06-02  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了转到:为template.ParseFiles指定模板文件名大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决转到:为template.ParseFiles指定模板文件名?

开发过程中遇到转到:为template.ParseFiles指定模板文件名的问题如何解决?下面主要结合日常开发的经验,给出你关于转到:为template.ParseFiles指定模板文件名的解决方法建议,希望对你解决转到:为template.ParseFiles指定模板文件名有所启发或帮助;

实用提示:

使用os.Getwd()filepath.Join()查找相对文件路径的绝对路径。

// file: showPath.go
package main
import (
        "fmt"
        "path/filepath"
        "os"
)
func main(){
        cwd, _ := os.Getwd()
        fmt.Println( filepath.Join( cwd, "./template/index.gtpl" ) )
}

首先,我建议该template文件夹仅包含用于演示的模板,而不包含go文件。

接下来,为了简化工作,仅运行根项目目录中的文件。这将有助于使文件路径与嵌套在子目录中的所有go文件保持一致。相对文件路径从当前工作目录(即从中调用程序的位置)开始。

显示当前工作目录中更改的示例

user@user:~/go/src/test$ go run showPath.go
/home/user/go/src/test/template/index.gtpl
user@user:~/go/src/test$ cd newFolder/
user@user:~/go/src/test/newFolder$ go run ../showPath.go 
/home/user/go/src/test/newFolder/template/index.gtpl

对于测试文件,您可以通过提供文件名来运行单个测试文件。

go test foo/foo_test.go

最后,使用基本路径和path/filepath包来形成文件路径。

例:

var (
  basePath = "./public"
  templatePath = filepath.Join(basePath, "template")
  indexfile = filepath.Join(templatePath, "index.gtpl")
)

解决方法

我当前的目录结构如下所示:

App
  - Template
    - foo.go
    - foo.tmpl
  - Model
    - bar.go
  - Another
    - Directory
      - baz.go

该文件foo.go用于ParseFiles在期间读入模板文件init

import "text/template"

var qTemplate *template.Template

func init() {
  qTemplate = template.Must(template.New("temp").ParseFiles("foo.tmpl"))
}

...

单元测试foo.go按预期工作。但是,我现在正在尝试对其进行单元测试,bar.go并且baz.go都将其导入,foo.go并且在尝试打开时会感到恐慌foo.tmpl

/App/Model$ go test    
panic: open foo.tmpl: no such file or directory

/App/Another/Directory$ go test    
panic: open foo.tmpl: no such file or directory

我尝试将模板名称指定为相对目录(“ ./foo.tmpl”),完整目录(“〜/ go / src / github.com / App / Template
/ foo.tmpl”),相对于应用程序目录(“
/App/Template/foo.tmpl”)和其他选项,但两种情况似乎都无效。单元测试失败或者bar.gobaz.go(或两者)。

我的模板文件应该放在哪里,应该如何调用,ParseFiles以便无论我go test从哪个目录调用都可以始终找到该模板文件?

大佬总结

以上是大佬教程为你收集整理的转到:为template.ParseFiles指定模板文件名全部内容,希望文章能够帮你解决转到:为template.ParseFiles指定模板文件名所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: