十一(11ty)数据分页-标题来自数据

Eleventy (11ty) Data Pagination - Title from data

尝试使用数据设置分页,其中 <head><title>{{ title }}</title></head> 中的 {{ title }} 中定义的 当前 页面的标题projects.json

假设可以做到:

# 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 }}

可能误解了一些基本原理,但 {{ title }} 呈现为 [object, object]。固定链接工作正常...

njk 文件中,通常不能在 frontmatter 中使用数据变量或模板语法。

永久链接变量是个例外。

official Eleventy documentation about permalink


要解决您的问题,您可以:

  • page.njk
  • 中硬编码 title
  • 使用 javascript .11ty.js 模板文件,替换 page.njkmain.njk,或作为 main.njk.[=38= 的布局]

.11ty.js 文件一般可以在frontmatter中使用数据变量。

例如.11ty.js 文件的前部变量:

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;

实际上可以使用主模板 main.njk 中的 {{ project.title }} 访问项目标题,就像 projects.json 中为该项目定义的任何其他项目数据一样。

对于任何其他页面(未定义为 projects.json 中的 object),可以使用条件语句:

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

这样:

# 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"
    }
]

输出:

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

现在eleventyComputed可以使用

# 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 }}"