0

How can I create a function in Go Templates? I am trying to loop through a directory tree passed into the template, but I don't know how to go about looping through subdirectories without creating a function in the template that'll call itself.

Here is some pseudocode for what I would like to do:

function loop(directory){
 for item in directory:
   if item.type == FOLDER:
     loop(item)
}

If anything's unclear, I'd be happy to clarify.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Serket
  • 3,785
  • 3
  • 14
  • 45
  • You want to create a function _in_ the template? That's not possible. You can register Go functions though which you can call from the templates. – icza Jan 21 '21 at 14:30
  • @icza could you provide an example? – Serket Jan 21 '21 at 14:41
  • Does this answer your question? [Call a method from a Go template](https://stackoverflow.com/questions/10200178/call-a-method-from-a-go-template) – blami Jan 21 '21 at 14:44
  • Use the `Template.Funcs()` method to register functions. – icza Jan 21 '21 at 14:52

1 Answers1

-1
package main

import (
    "fmt"
    "io/ioutil"
    "log"
)

func  loop(folder string){
    files, err := ioutil.ReadDir(folder)
    if err != nil {
        log.Fatal(err)
    }
    for _, f := range files {
        if f.IsDir() {
            loop(f.Name())
        }
        fmt.Println(f.Name())
    }
}
func main()  {

    loop(".")
}

dılo sürücü
  • 3,821
  • 1
  • 26
  • 28