How can I return array in golang to use it in my index.html?

huangapple go评论84阅读模式
英文:

How can I return array in golang to use it in my index.html?

问题

我有这段代码:

files, _ := ioutil.ReadDir("public/my-template/imagesT/gallery/")
for _, f := range files {
    fmt.Println(f.Name())
}

如何返回一个包含所有f.Name的数组,以便在index.html中使用它们?

英文:

I have this code

files, _ := ioutil.ReadDir("public/my-template/imagesT/gallery/")
	for _, f:=range files {
		fmt.Println(f.Name())
	}

How can return an array contain all f.Name to use them in index.html ?

答案1

得分: 2

创建一个切片,并在循环中使用append来添加文件名。

var fileNames []string
files, _ := ioutil.ReadDir("public/my-template/imagesT/gallery/")
for _, f := range files {
    fileNames = append(fileNames, f.Name())
}

// 现在fileNames包含了所有的文件名,你可以将它们传递给你的模板。

同时请注意你不应该忽略在以下代码行中可能返回的错误

```go
files, _ := ioutil.ReadDir("public/my-template/imagesT/gallery/")
英文:

Create a slice and use append to add the file names in your loop.

var fileNames []string
files, _ := ioutil.ReadDir("public/my-template/imagesT/gallery/")
for _, f := range files {
    fileNames = append(fileNames, f.Name())
}

// Now fileNames contains all of the file names for you to pass to your template.

Also note that you should not ignore the possible error returned on the line

files, _ := ioutil.ReadDir("public/my-template/imagesT/gallery/")

huangapple
  • 本文由 发表于 2016年3月14日 09:35:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/35978181.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定