Creating the List Layout

Up until this point, you’ve only worked with individual pages, like the home page or a project page. You haven’t done anything with lists of content yet. But if you’re looking to show a list of tags, categories, or in this case, projects, you have to define a layout for those named list.html. When you generated the theme, Hugo placed a list layout in the themes/basic/layouts/_default directory, but it’s blank. That’s why you don’t see anything when you visit http://localhost:1313/projects.

Let’s define a default list template that will work for all list pages on the site. Open the file themes/basic/layouts/_default/list.html and add the following code to the file, which displays the title of the content page and builds a list of links to each content page:

 {{ define "main" }}
 
  <h2>{{ .Title }}</h2>
  <ul>
  {{ range .Pages }}
  <li><a href=​"{{ .RelPermalink }}"​>{{ .Title }}</a></li>
  {{ end }}
  </ul>
 
 {{ end }}

The {{ range .Pages }} section is where the magic happens. The .Pages collection contains all of the pages related to the section you’re working with. When Hugo builds the list page for Projects, for example, it collects all the pages within content/projects and makes those available in the .Pages variable in the context. The range function lets you iterate over the results so you can display each record in the collection. Inside of the range block, you access the properties of each page, as the context is now set to that specific page’s context. In this case, you’re displaying the site-relative URL and title of each page.

Fire up the development server again with hugo server and visit http://localhost:1313/projects, and you’ll see a list of your projects. Notice that the heading on the page also shows “Projects”. The .Title variable at the top of the layout file uses the content type’s title:

images/content_sections/projects.png

With this in place, add a Projects link to your main navigation so visitors can find that section. In the exercises at the end of Chapter 2, Building a Basic Theme, you moved your navigation from the header partial to its own nav partial. Open themes/basic/layouts/partials/nav.html and add the link to the /projects url:

 <nav>
  <a href=​"/"​>Home</a>
  <a href=​"/about"​>About</a>
» <a href=​"/projects"​>Projects</a>
  <a href=​"/resume"​>Résumé</a>
  <a href=​"/contact"​>Contact</a>
 </nav>

The default list layout you made is very generic. It’s a good start and will serve you well when you add other content types to your site later. Let’s create more specific layouts for projects so you can make project pages look a little different.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.105.239