Learn how to break down your Hugo pages into smaller “components” with partials in this Hugo tutorial.
The idea behind a partial is simple: it’s a file that can be included into a layout to reduce repetition or simply hide some complexity. You’ll add a nav bar to your site with a partial. While you could add this logic directly to your
baseof.html, sometimes it’s nice to split a layout up into smaller partials so you don’t need to deal with a 2000-line file.
partials directory in your
layouts directory so the final path will be
/layouts/partials/. Inside create
nav.html with the following contents:
That’s the navigation taken care of. Now it’s time to include it in your layout. Open
/layouts/_default/baseof.html and add the following below
In Go, your single quotes are no good for strings, only double quotes designate a string.
Render your page, and there you have it.
Let’s try another scenario to demonstrate the power of partials. We will simplify
baseof.html even further by moving the contents of
<head> to a partial. Create
/layouts/partials/meta.html with the following content:
In this partial, we have variables that need the context of the current page. Lucky for you, passing the context of the current page can be done with a single character.
/layouts/_default/baseof.html and replace the contents of
<head> with the following:
. at the end is passing the context of the current page, which allows the partial to print out the current page’s title. You’ll see this come up a lot in your Hugo sites, just you wait.
In the next lesson we’ll go through the basics of Hugo templating and see how we can manipulate and iterate over data.