How to put variable value in string quotes? "$variable"

Dear hugo community,

I need a quick support in getting a json file from the data directory that has the same page title.

The page - list-type - name is “Tarek Oraby” , and the file name is “data/tarek oraby.json”

I wanted to assing .Title to a variable $ptitle and use it in my code below:

{{ $ptitle := .Title}}
<p>{{ (index .Site.Data "$ptitle").description }}</p>

How can I add a variable in quotes? or substitute a string with the variable’s value?

Thank you in advance

You need to change the title to lowercase to match the data filename, the data filename is case-sensitive.

{{ $ptitle := .Title}}
<p>{{ (index .Site.Data ($ptitle | lower)).description }}</p>

If you prefer the kebab case filename, for example, the following will match data/tarek-oraby.json.

{{ $ptitle := .Title}}
<p>{{ (index .Site.Data (replaceRE `\s` "-" $ptitle | lower)).description }}</p>

The snake case is similar, just replace the "-" with "_".

1 Like

BTW, the page’s parameters (front matter) seems a better place to store those meta (description) than a data file, take the foo category list page as an example.


title: Foo
description: Describe  the Foo category.
<p>{{ .Description }}</p>
1 Like

Thank you, thank you, thank you.
This worked.

The reason for the json file is that I want to put many parameters for each author: Like the nationality, degree, etc.

And wanted to be able to edit it once across the whole website.

You’re welcome, it may be helpful that specify a subfolder for those data files, to avoid being conflicted with other data files. For example, data/authors/tarek-oraby.json.

{{ $ptitle := .Title}}
{{ with index .Site.Data.authors (replaceRE `\s` "-" $ptitle | lower)) }}
  <p>{{ .description }}</p>
{{ end }}

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.