Skip to content

front matter thumbnails #15

@lzinga

Description

@lzinga

Currently, the library handles the content correctly but doesn’t fully support the front matter. This makes it challenging to display images when rendering content on a page, since the thumbnail is stored relative to the post itself. With the code below, I was able to successfully import and load the thumbnail.

---
thumbnail: .\example.jpg
---

In my query or import to list all the posts or content, the thumbnail object can be used together with an enhanced:img component. While I’m not certain if this functionality can be directly integrated into the library, it’s likely that some utility functions could be created to apply the same configuration and image properties used by the library and to use the same relative path lookup.

  const postModules = import.meta.glob('$lib/content/posts/**/*.{svx,md}', { eager: true });
  const imageModules = import.meta.glob('$lib/content/posts/**/*.{jpg,jpeg,png,webp,svg,avif}', { eager: true, query: { enhanced: true} });

  const allPosts: PostMeta[] = Object.entries(postModules)
    .map(([path, module]: any) => {
      const { metadata } = module;

      let resolvedThumbnail = null;
      if (metadata?.thumbnail) {
        if (metadata.thumbnail.startsWith('.')) {
          // Resolve relative image path based on the post file's directory
          const postDir = path.substring(0, path.lastIndexOf('/'));
          const resolvedPath = `${postDir}/${metadata.thumbnail.substring(2)}`; // remove leading './'
          // Find image import matching the resolved absolute path suffix
          const matchingImageKey = Object.keys(imageModules).find(key => key.endsWith(resolvedPath));
          if (matchingImageKey) {
            const imageImport = imageModules[matchingImageKey];
            resolvedThumbnail = imageImport?.default || imageImport;
          }
        } else {
          // For absolute or non-relative paths, fallback to simple endsWith match
          const matchingImageKey = Object.keys(imageModules).find(key => key.endsWith(metadata.thumbnail));
          if (matchingImageKey) {
            const imageImport = imageModules[matchingImageKey];
            resolvedThumbnail = imageImport?.default || imageImport;
          }
        }
      }


      return {
        ...metadata,
        thumbnail: resolvedThumbnail,
      };
    });

  return allPosts;

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions