HUGO

Does readFile work with page bundle?

readFile reads relative path with content dir, but does it work with page bundle?

How include a xx.go file under the same dir using the relative path xx.go, not the relative path to content dir xx/xx/xx/xx.go?

Structure

content
└── posts
    ├── post-1
    │   ├── index.md
    │   └── xx.go
    ├── post-2.md
    └── post-3.md

layouts/_default/single.html

{{ define "main" }}
  {{- $file := .Resources.GetMatch "xx.go" -}}
  {{- with $file -}}
    {{ .Content }}
  {{- end -}}
{{ end }}

See https://gohugo.io/content-management/page-resources

1 Like

Actually I have a lot of xx.go to be included in different files, if add them in single.html. it will be hard to maintain.

Use a shortcode.

content/posts/post-1/index.md

+++
title = "Post 1"
date = 2020-11-26T08:49:28-05:00
draft = false
+++
{{< readfile "xx.go" >}}

layouts/shortcodes/readfile.html

{{- with .Get 0 -}}
  {{- with $.Page.Resources.GetMatch . -}}
    {{ .Content }}
  {{- else -}}
    {{- errorf "Resource '%s' not found while rendering the '%s' shortcode. See %s" . $.Name $.Position -}}
  {{- end -}}
{{- else -}}
  {{- errorf "The '%s' shortcode requires a single positional parameter. See %s" .Name .Position -}}
{{- end -}}
2 Likes

This works well, thank you so much!

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