How to add different class to each Keyword?

Is there a smarter way of adding a new class to each keyword then doing the following:

In layout/_default/list.html

  {{range .Keywords}}
    {{if in . "Apple"}}
      class="red"
    {{else if in . "Kiwi"}}
      class="green"
        ...
    {{end}}
  {{end}}

The above works, but becomes repetitive with 5+ keywords.

For reference, in content/post.md

+++
title = ""
description = ""
keywords = ["Apple"]
+++

There is a trick I use to map complex or even simple data:

{{ $class := "" }}
{{ $mapping := `
Apple: red
Kiwi: green
Samsung: blue
` | transform.Unmarshal }}

{{ range .Keywords }}
  {{ with index $mapping . }}
    {{ $class = . }}
  {{ end }}
{{ end }}
<div class="{{ $class }}">[...]</div>

transform.Unmarshal can parse any json/yaml/toml string. Also, using backtick, you can have a multiple line strings in Go Template. The above example uses yaml to define a map of “keywords”/“color”.

The second part is, I think, pretty intuitive.

2 Likes

That was super cool. Thanks for sharing.

Question - Where would you normally place the class, mapping code if it’s to be

  • Reused in multiple sections (I assume in a partial?)
  • Just for a single section (I assume in the section/list or section/single?)

ps. Your Hugo blog posts have been super helpful.

If it’s global to the site, easiest route is to add it as a data file or as a Site param.

# data/class_mapping.yaml
Apple: red
Kiwi: green
Samsung: blue
{{ $mapping := .Site.Data.class_mapping }}

Now I’m not sure about yaml maps living at the root of a data file, you should check or use json or toml.

If it’s different depending on the section, you could add to the section front matter as part of the cascade key. This will make every page of that section inherit the value and will ease up on your retrieving it.

# content/my-section/_index.md
title: My Section
cascade:
  class_mapping:
     Apple: red
     Kiwi: green
     Samsung: blue
{{*/ layout/my-section/single.html */}}
{{ $mapping := .Params.class_mapping }}

If you add a page its own class_mapping Front Matter key it will overwrite its section’s cascade.

1 Like

Thanks for sharing. I’ll have to play around with this a bit to understand how everything works.

I’m new to several of the functions you’ve shared so learned a bunch of things today :smiley:

1 Like