paginationnunjucksyaml-front-mattereleventy

Eleventy (11ty) Data Pagination - Title from data


Trying to setup pagination with data, where {{ title }} in <head><title>{{ title }}</title></head> is the title of the current page as defined in projects.json

Assumed this could be done:

# main.njk

<head>
    <title>{{ title }}</title>
</head>
# page.njk

---
layout: main.njk
pagination:
    data: projects
    size: 1
    alias: project
permalink: "work/{{ project.title | slug }}/"
title: {{ project.title }}
---

Might have misunderstood some fundamentals but {{ title }} renders out as [object, object] instead. Permalink works fine...


Solution

  • The project title can actually be accessed with {{ project.title }} in the master template main.njk, as with any other project data defined for that project in projects.json.

    For any other page (not defined as an object in projects.json), a conditional statement can be used:

    <title>{{ project.title if project.title else title}}</title>

    So that:

    # main.njk
    
    <head>
        <title>{{ project.title if project.title else title}}</title>
    </head>
    
    # page.njk
    
    ---
    layout: main.njk
    pagination:
        data: projects
        size: 1
        alias: project
    permalink: "work/{{ project.title | slug }}/"
    ---
    
    # other_page.njk
    
    ---
    layout: main.njk
    title: Other Page
    ---
    
    # projects.json
    
    [
        {
            "title": "Project 1"
        },
        {
            "title": "Project 2"
        }
    ]
    

    Outputs:

    # work/project-1/
    
    <head>
        <title>Project 1</title>
    </head>
    
    # work/project-2/
    
    <head>
        <title>Project 2</title>
    </head>
    
    # other-page/
    
    <head>
        <title>Other Page</title>
    </head>