HUGO
News Docs Themes Community GitHub

urls.URLize

Returns the given string, sanitized for usage in a URL.

Syntax

urls.URLize INPUT

Returns

string

Alias

urlize

The anchorize and urlize functions are similar:

  • Use the anchorize function to generate an HTML id attribute value
  • Use the urlize function to sanitize a string for usage in a URL

For example:

{{ $s := "A B C" }}
{{ $s | anchorize }} → a-b-c
{{ $s | urlize }} → a-b-c

{{ $s := "a b   c" }}
{{ $s | anchorize }} → a-b---c
{{ $s | urlize }} → a-b-c

{{ $s := "< a, b, & c >" }}
{{ $s | anchorize }} → -a-b--c-
{{ $s | urlize }} → a-b-c

{{ $s := "main.go" }}
{{ $s | anchorize }} → maingo
{{ $s | urlize }} → main.go

{{ $s := "Hugö" }}
{{ $s | anchorize }} → hugö
{{ $s | urlize }} → hug%C3%B6

Example

Use the urlize function to create a link to a term page.

Consider this site configuration:

taxonomies:
  author: authors
[taxonomies]
  author = 'authors'
{
   "taxonomies": {
      "author": "authors"
   }
}

And this front matter:

---
authors:
- Victor Hugo
title: Les Misérables
---
+++
authors = ['Victor Hugo']
title = 'Les Misérables'
+++
{
   "authors": [
      "Victor Hugo"
   ],
   "title": "Les Misérables"
}

The published site will have this structure:

public/
├── authors/
│   ├── victor-hugo/
│   │   └── index.html
│   └── index.html
├── books/
│   ├── les-miserables/
│   │   └── index.html
│   └── index.html
└── index.html

To create a link to the term page:

{{ $taxonomy := "authors" }}
{{ $term := "Victor Hugo" }}
{{ with index .Site.Taxonomies $taxonomy (urlize $term) }}
  <a href="{{ .Page.RelPermalink }}">{{ .Page.LinkTitle }}</a>
{{ end }}

To generate a list of term pages associated with a given content page, use the GetTerms method on a Page object.