Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
June 10, 2022 12:41 am GMT

Hugo Partials

By Mike Neumegen

Brought to you by CloudCannon, the Git-based CMS for Hugo.

The idea behind a partial is simple: its a file that can be included into a layout to reduce repetition or simply hide some complexity. Youll add a nav bar to your site with a partial. While you could add this logic directly to your baseof.html, sometimes its nice to split a layout up into smaller partials so you dont need to deal with a 2000-line file.

Your first partial

Create a partials directory in your layouts directory so the final path will be /layouts/partials/. Inside create nav.html with the following contents:

    <nav>      <ul>        <li><a href="/">Home</a></li>        <li><a href="/about/">About</a></li>      </ul>    </nav>

Thats the navigation taken care of. Now its time to include it in your layout. Open /layouts/_default/baseof.html and add the following below <body>:

    {{ partial "nav.html" }}

In Go, your single quotes are no good for strings; only double quotes designate a string.

Render your page, and there you have it.

Your second partial

Lets 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:

    <meta charset="utf-8">    <title>{{ print .Page.Title }}</title>    {{ $style := resources.Get "sass/main.scss" | resources.ToCSS | resources.Minify }}    <link rel="stylesheet" href="{{ $style.Permalink }}">

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.

Open up /layouts/_default/baseof.html and replace the contents of <head> with the following:

    {{ partial "meta.html" . }}

That little . at the end is passing the context of the current page, which allows the partial to print out the current pages title. Youll see this come up a lot in your Hugo sites, just you wait.

Whats next?

In the next lesson well go through the basics of Hugo templating and see how we can manipulate and iterate over data.


Original Link: https://dev.to/cloudcannon/hugo-partials-no2

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To