data.GetCSV
语法
data.GetCSV SEPARATOR INPUT... [OPTIONS]
返回值
[][]string
别名
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 := dict }}
{{ $p := "data/pets.csv" }}
{{ with resources.Get $p }}
{{ $opts := dict "delimiter" "," }}
{{ $data = . | transform.Unmarshal $opts }}
{{ else }}
{{ errorf "Unable to get resource %q" $p }}
{{ end }}
页面资源替代方案
在访问页面资源时,请考虑将 Resources.Get
方法与 transform.Unmarshal
结合使用。
my-project/
└── content/
└── posts/
└── my-pets/
├── index.md
└── pets.csv
{{ $data := dict }}
{{ $p := "pets.csv" }}
{{ with .Resources.Get $p }}
{{ $opts := dict "delimiter" "," }}
{{ $data = . | transform.Unmarshal $opts }}
{{ else }}
{{ errorf "Unable to get resource %q" $p }}
{{ end }}
远程资源替代方案
在访问远程资源时,请考虑将 resources.GetRemote
函数与 transform.Unmarshal
结合使用,以改善错误处理和缓存控制。
{{ $data := dict }}
{{ $url := "https://example.org/pets.csv" }}
{{ with try (resources.GetRemote $url) }}
{{ with .Err }}
{{ errorf "%s" . }}
{{ else with .Value }}
{{ $opts := dict "delimiter" "," }}
{{ $data = . | transform.Unmarshal $opts }}
{{ else }}
{{ errorf "Unable to get remote resource %q" $url }}
{{ end }}
{{ end }}