3

I have some posts in Hugo with page resources that are SVG files that I want to include inline in the resulting HTML. For example, here's a typical folder structure:

content
+-- posts
    +-- somepost
        +-- index.md
        +-- diagram.svg

In the post, I'd like to include the content of diagram.svg inline as part of the resulting HTML. Reading through another related question, I created a shortcode to do that that looks like this:

{{- readFile (.Get 0) | safeHTML -}}

However, this means that I need to provide the full path to the SVG resource, which results in this in my markdown:

{{< readsvg "content/posts/somepost/diagram.svg" >}}

Ideally, I would like the shortcode to find the page resource so that the markdown can be simplified to:

{{< readsvg "diagram.svg" >}}

If I use the page resource functions, I can get the resource itself by doing: {{ $svg := $.Page.Resources.GetMatch (.Get 0) }} but the resulting file name is relative to the resource bundle while readFile needs it to be relative to the top of the project. How can I get the full path of the resource so that I can pass it to readFile?

I tried to use absURL to do that but this doesn't work as I have custom URLs on posts.

prosoitos
  • 6,679
  • 5
  • 27
  • 41
Bruno Girin
  • 175
  • 2
  • 10

2 Answers2

3

Thanks to ruddra for pointing me in the right direction, the full answer that worked was:

{{ $svgFile :=  (path.Join (path.Dir .Page.File.Path) (.Get 0)) }}
{{- readFile $svgFile | safeHTML -}}

If you want more flexibility in how you specify the resource in the markdown, you can add a resource match to that solution:

{{ $svgRes := .Page.Resources.GetMatch (.Get 0) }}
{{ $svgFile :=  (path.Join (path.Dir .Page.File.Path) $svgRes) }}
{{- readFile $svgFile | safeHTML -}}
Bruno Girin
  • 175
  • 2
  • 10
1

I think the svg file should be inside static directory. But still if you want to put it in same directory as the markdown files, probably you can use .File.Dir in the custom shortcode. Like this:

{{ $svgFile :=  print (.Page.File.Path) (.Get 0) }}
{{- readFile $svgFile | safeHTML -}}
ruddra
  • 50,746
  • 7
  • 78
  • 101