Adding a "last edited" timestamp? #345
-
Hi, I'm really enjoying using contentlayer! I've built a blog with Next.js and I'm planning to build documentation with it too. Like some documentation websites, I'd like to add a "last edited" timestamp as well as a link to the page source on GitLab. My current idea is to add it to computedFields under Post, and try to do git stuff in there to get the timestamp. Is this a sensible approach, or any other ideas? |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments
-
I am also interested in this |
Beta Was this translation helpful? Give feedback.
-
That would be nice! I'll be happy to help. |
Beta Was this translation helpful? Give feedback.
-
Hey guys, I figured it out. lastModified: {
type: 'string',
resolve: (post) => getFileInfo(`_blog/${post._raw.sourceFilePath}`).lastModified,
},
sourceUrl: {
type: 'string',
resolve: (post) => getFileInfo(`_blog/${post._raw.sourceFilePath}`).sourceUrl,
}, import { getLastModified } from './git';
interface FileInfo {
lastModified: string
sourceUrl: string
}
const getFileInfo = (filename: string): FileInfo => {
return {
lastModified: getLastModified(filename),
sourceUrl: `https://gitlab.com/soapbox-pub/soapbox.pub/-/blob/main/${filename}`,
};
};
export {
getFileInfo,
}; import { execFileSync } from 'child_process';
const getLastModified = (filename: string): string => {
const raw = execFileSync('git', ['log', '-1', '--pretty=%cI', filename]);
return String(raw).trim();
};
export {
getLastModified,
}; Finally, blog/[slug].tsx: {post.lastModified && (
<p className='text-gray-500 mt-12'>
Last edited <a className='text-azure' href={post.sourceUrl} target='_blank'>
<DateFormatter dateString={post.lastModified} />
</a>.
</p>
)} |
Beta Was this translation helpful? Give feedback.
Hey guys, I figured it out.
See: contentlayer.config.js
files.ts:
git.ts: