Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a list of values into comma separated string in Hugo template

Tags:

html

go

hugo

I am new to Hugo, know nothing about GoLang and I am trying to do the following.

Problem

I have a Hugo site, and in my posts, I specify keywords in the front matter like:

---
author: Andrea Tino
keywords:
- language
- image
- fun
---

In my template, I want to add a <meta> for keywords, so I have:

<head>
    <meta charset="utf-8">
    {{ if .Keywords }}
    <meta name="keywords" content="{{ .Keywords }}">
    {{ end }}
    <title>{{ .Title }} | {{ .Site.Title }}</title>
</head>

The problem, of course, is that I get this in the output:

<head>
    <meta charset="utf-8">
    <meta name="keywords" content="[language image fun]">
    <title>{{ .Title }} | {{ .Site.Title }}</title>
</head>

While my objective is to get:

<meta name="keywords" content="language, image, fun">

How to achieve this?


What I have tried

Looking at this documentation, I have tried to play a little:

{{ if .Keywords }}
<meta name="keywords" content="{{ .Keywords | println }}">
{{ end }}

Also tried:

{{ if .Keywords }}
<meta name="keywords" content="{{ .Keywords | printf "%s" }}">
{{ end }}

They do not work. Also tried:

{{ if .Keywords }}
<meta name="keywords" content="{{ println(strings.Join(.Keywords, ", ")) }}">
{{ end }}

This last one causes an error:

Error: "/Users/me/Git/myproj/themes/mytheme/layouts/partials/header.html:7:1": parse failed: template: partials/header.html:7: unexpected "(" in operand

like image 758
Andry Avatar asked Dec 22 '22 23:12

Andry


2 Answers

Can you try

<p>Keywords: {{ delimit .Keywords ", " }}</p>
like image 98
Sefa Şahinoğlu Avatar answered Feb 08 '23 22:02

Sefa Şahinoğlu


Only output the meta tag when keywords are in your front matter:

{{- with delimit .Keywords "," -}}
  <meta name="keywords" content="{{.}}">
{{ end }}
like image 42
Bit33 Avatar answered Feb 08 '23 23:02

Bit33