Hugo v0.112.0 introduced three new template functions:
-
The
math.Abs
function returns the absolute value of the given number.{{ math.Abs -2.1 }} --> 2.1
-
The
hugo.WorkingDir
function returns the absolute path to the root of your project.{{ hugo.WorkingDir }} --> /home/user/projects/my-hugo-site
This allows you to do this:
{{ with .File }} {{ strings.TrimPrefix hugo.WorkingDir .Filename }} {{ end }}
Which gives you something like this:
/content/en/posts/post-1.md
-
The
urls.JoinPath
function joins the provided elements into a URL string. Unlike thepath.Join
function,urls.JoinPath
retains the consecutive slashes in the protocol portion of a URL.{{ urls.JoinPath "https://example.org" "a" "b" }} --> https://example.org/a/b {{ path.Join "https://example.org" "a" "b" }} --> https:/example.org/a/b
In the
path.Join
example above, note that one of the two slashes in the protocol portion of the URL has been (undesirably) removed.
Here’s a practical example using hugo.WorkingDir
and urls.JoinPath
:
hugo.toml
[params.repository]
branch = 'master'
owner = 'gohugoio'
repo = 'hugoDocs'
service = 'GitHub'
urlPatternEdit = 'https://github.com/%s/%s/edit/%s/%s'
urlPatternView = 'https://github.com/%s/%s/blob/%s/%s'
layouts/partials/repository-link.html
{{- if $.page.File }}
{{- with site.Params.repository }}
{{- $path := strings.TrimPrefix hugo.WorkingDir $.page.File.Filename }}
{{- $href := "" }}
{{- $text := "" }}
{{- if eq $.action "edit" }}
{{- $href = printf .urlPatternEdit .owner .repo .branch $path | urls.JoinPath }}
{{- $text = printf "Edit this page on %s" .service }}
{{- else if eq $.action "view" }}
{{- $href = printf .urlPatternView .owner .repo .branch $path | urls.JoinPath }}
{{- $text = printf "View this page on %s" .service }}
{{- end }}
<div class="repository-link">
<a href="{{ $href }}" rel="external">{{ $text }}</a>
</div>
{{- end }}
{{- end -}}
layouts/_default/single.html
{{ partial "repository-link.html" (dict "action" "edit" "page" .) }}
{{ partial "repository-link.html" (dict "action" "view" "page" .) }}
rendered (HTML)
<div class="repository-link">
<a href="https://github.com/gohugoio/hugoDocs/edit/master/content/en/getting-started/quick-start.md" rel="external">Edit this page on GitHub</a>
</div>
<div class="repository-link">
<a href="https://github.com/gohugoio/hugoDocs/blob/master/content/en/getting-started/quick-start.md" rel="external">View this page on GitHub</a>
</div>
rendered (browser)
If you use GitLab, your site configuration will look something like:
[params.repository]
branch = 'main'
owner = 'jsmith'
repo = 'my-project'
service = 'GitLab'
urlPatternEdit = 'https://gitlab.com/%s/%s/-/edit/%s/%s'
urlPatternView = 'https://gitlab.com/%s/%s/-/blob/%s/%s'