Traversing Local Files

Traversing Local Files

Hugo includes a way to traverse local files. This is done using the ‘readDir’ function.

Using readDir

readDir takes a single string input that is relative to the root directory of the site. It returns an array of os.FileInfo

Let’s create a shortcode to build a file index with links using readDir.


<table style="width=100%">
<th>Size in bytes</th>
{{$dir := .Get "dir"}}
{{ $url := .Get "baseurl" }}

{{ $files := readDir $dir }}
    {{ range $files }}
                    <a href="{{$url}}{{.Name | urlize }}"> {{.Name}}</a>
     {{ end }}

Now lets use it to list the css files used on this site

{{< fileindex dir="static/css" baseurl="/css/" >}}

Is rendered as:

Size in bytes Name
4096 font-awesome