9

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...

S.S. Anne
  • 15,171
  • 8
  • 38
  • 76
ebisdal93461
  • 139
  • 7

3 Answers3

8

Now eleventyComputed can be used

# main.njk
<head>
 <title>{{ title }}</title>
</head>
# page.njk
---
layout: main.njk
pagination:
    data: projects
    size: 1
    alias: project
permalink: "work/{{ project.title | slug }}/"
eleventyComputed:
    title: "{{ project.title }}"
Deepak Gupta
  • 614
  • 1
  • 7
  • 14
  • `renderData` instead of `eleventyComputed` worked for me but this appears to be a deprecated feature according to this: https://www.11ty.dev/docs/advanced-order/. Time to upgrade. – Jeff S. Nov 05 '21 at 08:11
3

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>
ebisdal93461
  • 139
  • 7
0

In a njk file, you generally cannot use data variables or template syntax in the frontmatter.

The permalink variable is an exception.

See the official Eleventy documentation about permalink


To solve your issue, you could either:

  • hard-code your title in your page.njk
  • use a javascript .11ty.js templating file, either to replace page.njk or main.njk, or as a layout to main.njk.

.11ty.js files can generally use data variables in the frontmatter.

e.g. of a .11ty.js file with a variable in the frontmatter:

let thing = "whatever";

class Sample {
    data() {// data() is the .11ty.js equivalent of frontmatter
        return {
        myCustomFrontmatterVariable: thing,
        };
    }
    render(data){
        return data.content;
    }
}

module.exports = Sample;
Manube
  • 5,110
  • 3
  • 35
  • 59