如何在Sanity.io中为文档设置默认creationDate字段?
Alright, let's figure this out. You want a hidden, read-only createdDate field that's set automatically when a document is created or published—here are actionable ways to do this depending on your setup:
1. Static Site Generators (Hugo, Jekyll, etc.)
Most SSGs rely on front matter for document metadata, and they’ve got great built-in ways to handle this without manual edits:
- Auto-generate from Git: Tools like Hugo let you pull the first commit date directly from Git, so you never have to manually add or edit the
createdDatefield. Just enable Git info in your config:
Then in your templates, you can reference# Hugo config.toml example enableGitInfo = true.GitInfo.AuthorDateas the official creation date—this is completely hidden from editors and can’t be modified unless someone messes with Git history (which you can restrict with repo permissions). - Hide front matter field: If you prefer to set
createdDatemanually in front matter, just make sure your templates don’t render this field publicly. Editors can see it in the raw file, but you can add a comment reminding them not to edit it:--- title: My Project Doc createdDate: 2024-05-20 # DO NOT EDIT - auto-set on creation ---
2. Content Management Systems (CMS)
If you’re using a CMS (WordPress, Contentful, custom tools), this is straightforward:
- Use built-in fields: Most CMS platforms already have a "Created Date" field that’s read-only by default (only admins might have permission to tweak it). Just ensure it’s set to hidden in the editor interface so content creators don’t even see it.
- Database-level enforcement: For custom CMS setups, configure your
createdDatedatabase column to default to the current timestamp on insertion, and lock it from updates:
Then hide the field in your CMS’s edit form so users can’t interact with it at all.-- Example SQL for MySQL ALTER TABLE documents ADD COLUMN createdDate DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL; ALTER TABLE documents MODIFY COLUMN createdDate DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL;
3. Plain Markdown Files (No Build Tools)
For standalone Markdown files, you can tuck the creation date away where it won’t be visible or accidentally edited:
- HTML comments: Store the date in a comment that won’t render when the file is converted to HTML:
<!-- createdDate: 2024-05-20 --> # My Document Title ...content here... - Front matter (hidden from rendering): Use YAML/TOML front matter, but make sure any tool you use to view the document ignores this field. Most Markdown viewers won’t display front matter by default, so this keeps it hidden from casual readers.
If you’re working with a specific tool or platform that I didn’t cover, drop a note and I can refine this further!
内容的提问来源于stack exchange,提问作者JAM
相关产品推荐
相关产品推荐

