Using existing layout code to generate json

Hi there,

I currently use this code on the list page to generate cards of all the pages in the section.

{{ $resultsPerPage := 18 }} <!-- Set the number of results per page -->
{{ $allPages := where .Site.RegularPages "Section" "properties-for-sale" }}
{{ $sortedPages := sort $allPages ".Params.title" "desc" }}
{{ $paginator := .Paginate $sortedPages $resultsPerPage }}
{{ $currentPageNumber := $paginator.PageNumber }}
{{ range $paginator.Pages }}
{{ partial "components/card.html" . }}
{{ end }}

How can I tell Hugo to also generate a .json file of all these pages?

do not understand the execute as template for json.


I created a JSON feed for my site, you will find the templates in my samples.

JSON template
Strip it down for your needs

must activate it in the config of the site and theme
You can put all in one config file.


1 Like

Thanks for the response @ju52

Very impressive setup in the config.toml didn’t even know some of these options existed.

so basically I can range the same way I range for cards and use a template like this

  {{ $allPages := where .Site.RegularPages "Section" "properties-for-sale" }}
  {{ $sortedPages := sort $allPages ".Params.title" "desc" }}
  {{- range $sortedPages -}}
    "title": "{{ .Title }}",
    "date": "{{ .Date }}",
    "content": "{{ .Content }}"
  }{{ if not (last $sortedPages) }},{{ end }}
  {{- end -}}

Now in your example home.json.json template in default generate .json file for home page. but in my option where I want to use it for a section such as


Should I place the json template in layouts/properties-for-sale/default.json.json or name it properties-for-sale.json.json in the _default directory


The Main issue

The main issue is the json file generates the same time as the cards are generated. I want the json to generate after the card generation so it can get the image url required for the card display etc.

Working with JSON, you will get a much easier life is you do something like this:

{{ $items := slice }}
{{ range $sortedPages }}
{{ $items = $items | append (dict 
   "title" .Title 
   "date" .Date 
   "content" .Content 
{{ end }}
{{ $json := $items | jsonify }}

Also, to publish some JSON there are several ways to go about it. I would say that:

  • If you need JSON for all/many pages, look into custom output formats.
  • If you need an ad hoc JSON file (e.g. for search indexing), using resources.FromString should be simpler:
 {{ $r := resources.FromString "foo/bar.json" $json }}
<a href="{{ $r.RelPermalink }}">Download JSON</a>
1 Like

Thanks @bep

This really save a lot of hassle to generate line by line code.


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