Easiest way to embed code from source files

I want to automatically embed code from .go files highlighted in my post (markdown or html, doesn’t matter). What is the easiest way to do so with Hugo?

Here are some more details of what I’m planning:

  • I want to have a folder of source code files, like example1.go.
  • I want to store metadata to these files in a JSON file, like
    { "name": "example1", "author": "me", "output": "hello world" }.
    It doesn’t matter if its one big JSON file or multiple.
  • I want to create a post that contains the metadata and the code. One post will always have exactly one code example and one example is only embedded into one post.

I think I know how to read the metadata and include it into the post, but how could I include the code?

Thanks for helping!

Please clarify:

  1. Will one post ever display multiple examples?
  2. Will one example ever be displayed on multiple posts?
  3. Does the metadata file contain information for all examples, or will there be a unique metadata file for each example, or for each page of example(s)?

I’ve added the information you asked for to my question.

Here’s an example:

git clone --single-branch -b hugo-forum-topic-36662 https://github.com/jmooring/hugo-testing hugo-forum-topic-36662
cd hugo-forum-topic-36662
hugo server

structure

content/
└── examples
    ├── example-1.md
    ├── example-2.md
    └── example-3.md
data/
└── examples.json
assets/
└── examples
    ├── example-1.go
    ├── example-2.py
    └── example-3.js
layouts/
├── _default
│   ├── baseof.html
│   ├── home.html
│   ├── list.html
│   └── single.html
└── examples
    └── single.html

And this is the code in layouts/examples/single.html that ties it all together

{{ $key := path.Base .TranslationKey }}

{{ with resources.GetMatch (printf "examples/%s.*" $key) }}
  <h2>Code</h2>
  {{ $lang := path.Ext .Name | strings.TrimLeft "."  }}
  {{ $options := slice "lineNos=table" "style=native" }}
  {{ transform.Highlight .Content $lang (delimit $options ",") }}
{{ end }}

{{ with index site.Data.examples $key }}
  <h2>Data</h2>
  Author: {{ .author }}<br>
  Output: {{ .output }}<br>
{{ end }}
3 Likes

I had not seen .TranslationKey being used this way. Is there a specific reason to use that? I would have just used {{ $key := .File.BaseFileName }}. So I am curious to know if using .TranslationKey is just a preference or it does something better.

I’m trying to think forward, when pages aren’t necessarily backed by files. Might as well get into the habit…

2 Likes

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