Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go: Specifying template filenames for template.ParseFiles

Tags:

go

My current directory structure looks like the following:

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

The file foo.go uses ParseFiles to read in the template file during init.

import "text/template"

var qTemplate *template.Template

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

...

Unit tests for foo.go work as expected. However, I am now trying to run unit tests for bar.go and baz.go which both import foo.go and I get a panic on trying to open 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

I've tried specifying the template name as a relative directory ("./foo.tmpl"), a full directory ("~/go/src/github.com/App/Template/foo.tmpl"), an App relative directory ("/App/Template/foo.tmpl"), and others but nothing seems to work for both cases. The unit tests fail for either bar.go or baz.go (or both).

Where should my template file be placed and how should I call ParseFiles so that it can always find the template file regardless of which directory I call go test from?

like image 484
Bill Avatar asked Sep 26 '13 17:09

Bill


1 Answers

Helpful tip:

Use os.Getwd() and filepath.Join() to find the absolute path of a relative file path.

Example

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

First off, I recommend that the template folder only contain templates for presentation and not go files.

Next, to make life easier, only run files from the root project directory. This will help make the path to an file consistent throughout go files nested within sub directories. Relative file paths start from where the current working directory, which is where the program was called from.

Example to show the change in current working directory

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

As for test files, you can run individual test files by supplying the file name.

go test foo/foo_test.go

Lastly, use a base path and the path/filepath package to form file paths.

Example:

var (
  basePath = "./public"
  templatePath = filepath.Join(basePath, "template")
  indexFile = filepath.Join(templatePath, "index.gtpl")
) 
like image 167
Larry Battle Avatar answered Oct 18 '22 12:10

Larry Battle