nuxt / content

The file-based CMS for your Nuxt application, powered by Markdown and Vue components.
https://content.nuxt.com
MIT License
3.08k stars 624 forks source link

fetchContentNavigation() option, to fetch additional variables from pages #2467

Closed davision closed 9 months ago

davision commented 9 months ago

fetchContentNavigation() method now works really great, but for some cases it really lack additional data to build navigation with let say, an icon or a description. Currently, the returned object only consists of page title and _path. I see that title is already fetched from the page header section.

Would it be cool, if the page have such header:

---
title: About Us
description: This is about us page
icon: mdi:account-group
---

And then when calling fetchContentNavigation(), I would have this extra info in the object as well:

[
  {
    "title": "About Us",
    "_path": "/about",
    "description": "This is about us page",
    "icon": "mdi:account-group"
  }
]

Or is there any other existing way to achieve this?

davision commented 9 months ago

There is a work around with combination of queryContent(), but I feel is an unnecessary extra computing:


const { data: content } = await useAsyncData("content", () =>
    queryContent().only(["_path", "title", "description", "icon"]).find()
);

const { data: navigation } = await useAsyncData("navigation", () =>
    fetchContentNavigation()
);

function mergeObjects(nav, extra) {
    const extraMap = extra.reduce((acc, item) => {
        acc[item._path] = item;
        return acc;
    }, {});

    function mergeChildren(item) {
        if (item.children) {
            item.children.forEach(mergeChildren);
        }

        const matchingExtra = extraMap[item._path];
        if (matchingExtra) {
            item.description = matchingExtra.description;
            item.icon = matchingExtra.icon;
        }
    }

    nav.forEach(mergeChildren);

    return nav;
}

const headerNavigation = mergeObjects(navigation.value, content.value);
davision commented 9 months ago

Ok, I am too lazy to read the documentation, apparently :)

navigation:
  title: 'Home'
  icon: '🏡'
davision commented 9 months ago

Implemented