【问题标题】:how to fetch the frontmatter of any hugo markdown page (not just _index.md)如何获取任何 hugo markdown 页面的 frontmatter(不仅仅是 _index.md)
【发布时间】:2019-05-10 14:57:03
【问题描述】:

我正在尝试为我的 hugo 网站编写一个短代码,用于获取页面的标题参数。

我有一个这样的目录结构:

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

这很好用:

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

而且这个始终是空白的(即使降价中有一个标题)。

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

我的问题是:如何获得独立页面的标题?

我尝试了很多不同的组合,但我做的不对。我已经尝试阅读文档,但他们在这一点上非常复杂。

【问题讨论】:

    标签: hugo hugo-shortcode


    【解决方案1】:

    我有办法!我编写了一个 Python3.7 小脚本来创建目录以及移动和重命名 Markdown 文件,然后在我的整个内容目录中运行它。这解决了我的问题,但有点破解......

    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')
    
    

    【讨论】:

      【解决方案2】:

      两个区别:

      • 使用全局站点变量
      • 只需将页面名称作为参数传递
      {{ with site.GetPage "workshops/bar" }}
      {{ .Title }}
      {{ end }}
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-01-18
        • 2021-10-19
        • 2018-10-22
        • 1970-01-01
        • 1970-01-01
        • 2017-01-25
        相关资源
        最近更新 更多