diff --git a/CHANGELOG.md b/CHANGELOG.md index 08ea60e5..48cf6741 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,7 @@ - [#586](https://github.com/estruyf/vscode-front-matter/issues/586): Allow to specify the content card fields - [#588](https://github.com/estruyf/vscode-front-matter/issues/588): Added extensibility support to override card fields - [#591](https://github.com/estruyf/vscode-front-matter/issues/591): Support for date format in the `datetime` field +- [#593](https://github.com/estruyf/vscode-front-matter/issues/593): Add support for date formatting in the preview path ### ⚡️ Optimizations diff --git a/src/helpers/processFmPlaceholders.ts b/src/helpers/processFmPlaceholders.ts index 4dda9ee7..e1133496 100644 --- a/src/helpers/processFmPlaceholders.ts +++ b/src/helpers/processFmPlaceholders.ts @@ -1,15 +1,49 @@ +import { format } from 'date-fns'; + export const processFmPlaceholders = (value: string, fmData: any) => { + // Example: {{fm.date}} or {{fm.date | dateFormat 'DD.MM.YYYY'}} if (value && value.includes('{{fm.')) { - const regex = new RegExp('{{fm.(\\w+)}}', 'g'); + const regex = /{{fm.[^}]*}}/g; const matches = value.match(regex); if (matches) { for (const match of matches) { - const field = match.replace('{{fm.', '').replace('}}', ''); - const fieldValue = fmData[field]; + const placeholderParts = match.split('|'); - if (fieldValue) { - value = value.replace(match, fieldValue); + if (placeholderParts.length > 1) { + const field = placeholderParts[0].replace('{{fm.', '').trim(); + const formatting = placeholderParts[1].trim().replace('}}', ''); + + // Get the field value + const fieldValue = fmData[field]; + + if (formatting.startsWith('format')) { + let dateFormat = formatting.replace('format:', '').trim(); + + // Strip the single quotes + if (dateFormat.startsWith("'") && dateFormat.endsWith("'")) { + dateFormat = dateFormat.substring(1, dateFormat.length - 1); + } + + // Parse the date value and format it + if (fieldValue) { + const formattedDate = format(new Date(fieldValue), dateFormat); + value = value.replace(match, formattedDate); + } + } else if (fieldValue) { + value = value.replace(match, fieldValue); + } + } else { + // Get the field name + const field = match.replace('{{fm.', '').replace('}}', ''); + + // Get the field value + const fieldValue = fmData[field]; + + // Replace the placeholder with the field value + if (fieldValue) { + value = value.replace(match, fieldValue); + } } } }