data.GetCSV
Syntax
data.GetCSV 分隔符 输入... [选项]
Returns
[][]string
Alias
getCSV
给定以下目录结构:
my-project/
└── other-files/
└── pets.csv
可以通过以下方式访问数据:
{{ $data := getCSV "," "other-files/pets.csv" }}
{{ $data := getCSV "," "other-files/" "pets.csv" }}
可以通过以下方式访问远程数据:
{{ $data := getCSV "," "https://example.org/pets.csv" }}
{{ $data := getCSV "," "https://example.org/" "pets.csv" }}
结果数据结构是一个数组的数组:
[
["name","type","breed","age"],
["Spot","dog","Collie","3"],
["Felix","cat","Malicious","7"]
]
选项
通过提供一个选项映射来添加请求头:
{{ $opts := dict "Authorization" "Bearer abcd" }}
{{ $data := getCSV "," "https://example.org/pets.csv" $opts }}
使用切片添加多个请求头:
{{ $opts := dict "X-List" (slice "a" "b" "c") }}
{{ $data := getCSV "," "https://example.org/pets.csv" $opts }}
全局资源替代方案
在访问全局资源时,可以考虑使用resources.Get
函数与transform.Unmarshal
结合使用。
my-project/
└── assets/
└── data/
└── pets.csv
{{ $data := "" }}
{{ $p := "data/pets.csv" }}
{{ with resources.Get $p }}
{{ $opts := dict "delimiter" "," }}
{{ $data = . | transform.Unmarshal $opts }}
{{ else }}
{{ errorf "无法获取资源 %q" $p }}
{{ end }}
页面资源替代方案
在访问页面资源时,可以考虑使用Resources.Get
方法与transform.Unmarshal
结合使用。
my-project/
└── content/
└── posts/
└── my-pets/
├── index.md
└── pets.csv
{{ $data := "" }}
{{ $p := "pets.csv" }}
{{ with .Resources.Get $p }}
{{ $opts := dict "delimiter" "," }}
{{ $data = . | transform.Unmarshal $opts }}
{{ else }}
{{ errorf "无法获取资源 %q" $p }}
{{ end }}
远程资源替代方案
在访问远程资源时,可以考虑使用resources.GetRemote
函数与transform.Unmarshal
结合使用,以改进错误处理和缓存控制。
{{ $data := "" }}
{{ $u := "https://example.org/pets.csv" }}
{{ with resources.GetRemote $u }}
{{ with .Err }}
{{ errorf "%s" . }}
{{ else }}
{{ $opts := dict "delimiter" "," }}
{{ $data = . | transform.Unmarshal $opts }}
{{ end }}
{{ else }}
{{ errorf "无法获取远程资源 %q" $u }}
{{ end }}