Skip to content

Commit

Permalink
add some meta vars to the template engine
Browse files Browse the repository at this point in the history
  • Loading branch information
atomicptr committed Jul 24, 2024
1 parent eea0539 commit d9721ed
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 5 deletions.
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,15 @@ The \[...\] part is variable and will as you can see above also be exported to t

You could also create a template like this "\[controllerName\]Controller.php" which would also match for "IndexController" to make even more precise templates

## Meta template variables

tmplr also has some extra template variables that you don't have to specify like:

- \_cwd - The current working directory
- \_path - The absolute path of your new file, e.g. pkg/cli/test.go will use "/home/YOURNAME/dev/tmplr/pkg/cli/test.go" here
- \_dirname - The name of the directory the new file is in, e.g. pkg/cli/test.go will use "cli" here
- \_filename - The name of the file, e.g. pkg/cli/test.go will use "test.go" here

## Name

tmplr comes from a mixture of template and Templar and is also supposed to be pronounced "Templar".
Expand Down
29 changes: 24 additions & 5 deletions pkg/cli/cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package cli
import (
"fmt"
"os"
"path/filepath"

"github.com/atomicptr/tmplr/pkg/fs"
"github.com/atomicptr/tmplr/pkg/meta"
Expand Down Expand Up @@ -47,11 +48,21 @@ func Run() error {
return err
}

cwd, err := os.Getwd()
if err != nil {
return err
}

for _, arg := range flag.Args() {
matchingTemplates := tmpl.FindMatchingTemplates(arg, templateFiles)
p, err := filepath.Abs(arg)
if err != nil {
return err
}

matchingTemplates := tmpl.FindMatchingTemplates(p, templateFiles)

if len(matchingTemplates) == 0 {
f, err := fs.OpenFile(arg)
f, err := fs.OpenFile(p)
if err != nil {
return err
}
Expand All @@ -67,7 +78,7 @@ func Run() error {
var templates []*tmpl.Template

for _, templateFile := range matchingTemplates {
template, err := tmpl.LoadTemplate(arg, templateFile)
template, err := tmpl.LoadTemplate(p, templateFile)
if err != nil {
return err
}
Expand Down Expand Up @@ -109,14 +120,22 @@ func Run() error {
selected.Data[userVar.Name] = val
}

// add some vars that are always present
selected.Data["_cwd"] = cwd
selected.Data["_path"] = p
selected.Data["_dirname"] = filepath.Base(filepath.Dir(p))
selected.Data["_filename"] = filepath.Base(p)

fmt.Println(selected.Data)

data, err := selected.Render()
if err != nil {
return err
}

f, err := fs.OpenFile(arg)
f, err := fs.OpenFile(p)
if err != nil {
return fmt.Errorf("could not create file %s: %w", arg, err)
return fmt.Errorf("could not create file %s: %w", p, err)
}
defer (func() {
err := f.Close()
Expand Down

0 comments on commit d9721ed

Please sign in to comment.