DEV Community

Cover image for [Hugo]: Sitemap.xml
Anastasiia_Berest
Anastasiia_Berest

Posted on

1

[Hugo]: Sitemap.xml

Hi. Today I will show you my Hugo template for generation Sitemap.xml.

First what you must do is go to: layouts/_default and create sitemap.xml. The code inside look like this:

{{ printf "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\" ?>" | safeHTML }}
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
  xmlns:xhtml="http://www.w3.org/1999/xhtml">
  {{ range .Data.Pages }}
  <url>
    <loc>{{ .RelPermalink }}</loc>
    {{ if not .Lastmod.IsZero }}
    <lastmod>
    {{ safeHTML ( .Lastmod.Format "20018-01-02T15:04:05-07:00" ) }}
    </lastmod>
    {{ end }}

    {{ with .Sitemap.ChangeFreq }}
    <changefreq>{{ . }}</changefreq>
    {{ end }}

    {{ if ge .Sitemap.Priority 0.0 }}


    {{ if eq .RelPermalink .Site.BaseURL }}

    <priority> 1 </priority>

    {{ end }}


    {{ $urlCheck := .RelPermalink | relURL }}
    {{ $urlSub2 := findRE "([^/]+).*" .RelPermalink 1 }}

    {{ $urlSubFix := replaceRE "[^/]*?((?:/[^/]*?){2})$" "$1" .RelPermalink }}


    {{ if eq $urlCheck $urlSubFix  }}
    <priority> 0.8 </priority>
    {{ end }}


    {{ if not ( eq .RelPermalink .Site.BaseURL | or ( eq $urlCheck $urlSubFix )) }}
    <priority> 0.6 </priority>
    {{ end }}


    {{ end }}

    {{ if .IsTranslated }}{{ range .Translations }}
    <xhtml:link
      rel="alternate"
      hreflang="{{ .Lang }}"
      href="{{ .RelPermalink }}"
      />{{ end }}
      <xhtml:link
        rel="alternate"
        hreflang="{{ .Lang }}"
        href="{{ .RelPermalink }}"
        />{{ end }}
      </url>
      {{ end }}
    </urlset>
Enter fullscreen mode Exit fullscreen mode

Don't forgot paste inside root folder in file config.toml this code:

[sitemap]
ChangeFreq = "daily"
Priority = 0.6
Weight = [["main", "1"], ["sub2", "0.8"], ["sub3", "0.6"]]
enableRobotsTXT = true
Enter fullscreen mode Exit fullscreen mode

The result sitemap looks like this: 
Image description

We have for main page priority index 1, for pages level 1, like /section/ - priority 0.8 and for pages level 2, like /section/posts - priority 0.6.
$urlSubFix - check url like /section/posts/ and save only /posts/ (priority 0.6) and for url like /section/ it saves /section/ (priority 0.8), it makes the pattern in $urlSubFix regexp.

Hugo SSG official documentation for sitemap.

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay