如何在 Hugo 模板中将值列表转换为逗号分隔的字符串
How to convert a list of values into comma separated string in Hugo template
我是 Hugo 的新手,对 GoLang 一无所知,我正在尝试执行以下操作。
问题
我有一个 Hugo 网站,在我的帖子中,我在前面的内容中指定 keywords
,例如:
---
author: Andrea Tino
keywords:
- language
- image
- fun
---
在我的模板中,我想为关键字添加一个 <meta>
,所以我有:
<head>
<meta charset="utf-8">
{{ if .Keywords }}
<meta name="keywords" content="{{ .Keywords }}">
{{ end }}
<title>{{ .Title }} | {{ .Site.Title }}</title>
</head>
当然,问题是我在输出中得到了这个:
<head>
<meta charset="utf-8">
<meta name="keywords" content="[language image fun]">
<title>{{ .Title }} | {{ .Site.Title }}</title>
</head>
虽然我的 objective 是得到:
<meta name="keywords" content="language, image, fun">
如何实现?
我试过的
看着这个documentation,我试玩了一下:
{{ if .Keywords }}
<meta name="keywords" content="{{ .Keywords | println }}">
{{ end }}
也尝试过:
{{ if .Keywords }}
<meta name="keywords" content="{{ .Keywords | printf "%s" }}">
{{ end }}
它们不起作用。也试过:
{{ if .Keywords }}
<meta name="keywords" content="{{ println(strings.Join(.Keywords, ", ")) }}">
{{ end }}
最后一个导致错误:
Error: "/Users/me/Git/myproj/themes/mytheme/layouts/partials/header.html:7:1": parse failed: template: partials/header.html:7: unexpected "(" in operand
你能试试吗
<p>Keywords: {{ delimit .Keywords ", " }}</p>
仅当关键字位于您的前面时才输出元标记:
{{- with delimit .Keywords "," -}}
<meta name="keywords" content="{{.}}">
{{ end }}
我是 Hugo 的新手,对 GoLang 一无所知,我正在尝试执行以下操作。
问题
我有一个 Hugo 网站,在我的帖子中,我在前面的内容中指定 keywords
,例如:
---
author: Andrea Tino
keywords:
- language
- image
- fun
---
在我的模板中,我想为关键字添加一个 <meta>
,所以我有:
<head>
<meta charset="utf-8">
{{ if .Keywords }}
<meta name="keywords" content="{{ .Keywords }}">
{{ end }}
<title>{{ .Title }} | {{ .Site.Title }}</title>
</head>
当然,问题是我在输出中得到了这个:
<head>
<meta charset="utf-8">
<meta name="keywords" content="[language image fun]">
<title>{{ .Title }} | {{ .Site.Title }}</title>
</head>
虽然我的 objective 是得到:
<meta name="keywords" content="language, image, fun">
如何实现?
我试过的
看着这个documentation,我试玩了一下:
{{ if .Keywords }}
<meta name="keywords" content="{{ .Keywords | println }}">
{{ end }}
也尝试过:
{{ if .Keywords }}
<meta name="keywords" content="{{ .Keywords | printf "%s" }}">
{{ end }}
它们不起作用。也试过:
{{ if .Keywords }}
<meta name="keywords" content="{{ println(strings.Join(.Keywords, ", ")) }}">
{{ end }}
最后一个导致错误:
Error: "/Users/me/Git/myproj/themes/mytheme/layouts/partials/header.html:7:1": parse failed: template: partials/header.html:7: unexpected "(" in operand
你能试试吗
<p>Keywords: {{ delimit .Keywords ", " }}</p>
仅当关键字位于您的前面时才输出元标记:
{{- with delimit .Keywords "," -}}
<meta name="keywords" content="{{.}}">
{{ end }}