Skip to content

SwiftToolkit/frontmatter

Repository files navigation

Frontmatter

A Swift package for parsing YAML frontmatter from files, providing a simple and type-safe way to extract and decode frontmatter metadata.

This package is a wrapper around Yams, providing a convenient API specifically for frontmatter parsing and encoding.

Installation

Add the following to your Package.swift package dependencies:

dependencies: [
    .package(url: "https://github.com/swifttoolkit/frontmatter.git", from: "1.0.0")
]

Then add Frontmatter to your target dependencies:

targets: [
    .target(
        name: "YourTarget",
        dependencies: .product(name: "Frontmatter", package: "frontmatter")
    )
]

Usage

Reading

The package provides several ways to decode frontmatter:

From a file:

struct Metadata: Codable {
    let title: String
    let date: String
    let tags: [String]
}

let metadata = try Frontmatter.decode(Metadata.self, file: "path/to/file.md")

From a string:

let contents = """
---
title: My Post
date: 2024-03-20
tags: ["swift", "coding"]
---

Post content here...
"""

let metadata = try Frontmatter.decode(Metadata.self, contents: contents)

From Data:

let data = try Data(contentsOf: myFileURL)
let metadata = try Frontmatter.decode(Metadata.self, data: data)

Writing

You can also encode any Decodable type, and set it as the frontmatter for a file or a string. When encoding to an existing file or string that already has frontmatter, the package will automatically replace the existing frontmatter while preserving the rest of the content.

let metadata = Metadata(
    title: "My Post",
    date: "2025-03-20",
    tags: ["swift", "coding"]
)
try Frontmatter.encode(metadata, to: "path/to/file.md")

The encode methods return a WriteResult indicating what happened:

  • .created: A new file was created
  • .added: Frontmatter was added to an existing file without frontmatter
  • .updated: Existing frontmatter was updated in the file

Alternatively, you can use the encode method to encode and get a string:

let initialContents = "Some initial content"
let updatedContents = try Frontmatter.encode(metadata, contents: initialContents)

The code above will return the following string:

---
title: My Post
date: '2025-03-20'
tags:
- swift
- coding
---

Some initial content

Format

The frontmatter should be:

  • Enclosed between --- separators
  • At the beginning of the file
  • Valid YAML format

Example:

---
title: My Post
date: 2024-03-20
tags: ["swift", "coding"]
---

A post content here...

Requirements

  • Swift 6.0+

About

Read and update Frontmatter contents in Swift

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages