Search code examples
hugohugo-shortcode

how to fetch the frontmatter of any hugo markdown page (not just _index.md)


I'm trying to write a shortcode for my hugo site that fetches the title parameter of page.

I have a directory structure like this:

content
├── workshops
│   ├── foo
│   │   └── _index.md
│   ├── bar.md

This works perfectly:

{{ with .Site.GetPage "home" "workshops/foo"}}
{{ .Params.Title }}
{{ end }}

And this one consistently comes up blank (even though there is a title in the markdown).

{{ with .Site.GetPage "home" "workshops/bar"}}
{{ .Params.Title }}
{{ end }}

My question is: How so I get the title of a standalone page?

I've tried a bunch of different combinations of things and I'm just not coming right. I've tried reading the docs and they are horribly convoluted on this point.


Solution

  • I have a solution! I wrote a little Python3.7 script to make directories and move and rename markdown files and just ran it over my entire contents directory. This solved my problem but is a bit of a hack...

    import logging
    import os
    from pathlib import Path
    
    def fixup(path):
        location = Path(path)
        assert location.is_dir(), location
        for child in location.iterdir():
            if child.is_dir():
                fixup(child)
            else:
                fix_file(child)
    
    
    def fix_file(file_path):
        name = file_path.name
        if not name.endswith(".md"):
            # we only care about markdown files.
            return
        check_metadata(file_path)
        if name.startswith("_index."):
            # looks good
            return
        # make a directory with the same name as the file (without the extension)
        suffix = ''.join(file_path.suffixes)
        prefix = name[: -len(suffix)]
    
        new_dir = file_path.parent / prefix
        new_dir.mkdir()
    
        new_path = new_dir / f"_index{suffix}"
        file_path.rename(new_path)
    
    
    
    def check_metadata(file_path):
        """ given the path to a markdown file, make sure that the frontmatter includes
        the required metadata
        """
        # TODO
        # required = ['title']
        # allowed  = ['pre', 'weight', 'ready']
    
    if __name__ == '__main__':
        fixup('content')