groue / GRMustache.swift

Flexible Mustache templates for Swift
http://mustache.github.com/
MIT License
594 stars 155 forks source link

Feature request: `Encodable` support for custom types #97

Open CharlesJS opened 3 months ago

CharlesJS commented 3 months ago

Have you given any thought to writing an Encoder that serializes to a MustacheBox? Since Codable conformances can be generated automatically a lot of the time, this would allow you to pretty closely replicate the seamless functionality that you currently have with NSObject subclasses, but with pure Swift types.

fumito-ito commented 2 months ago

Hello, @CharlesJS

Thank you for your feedback.

At this time, we do not have plans to create a custom encoder that conforms to Codable. However, if you wish to address this easily, you might consider adding a code snippet like the one below.

import Mustache

extension Encodable {
    var mustacheObject: MustacheBox? {
        guard
            let data = try? JSONEncoder().encode(self),
            let dictionary = try? JSONSerialization.jsonObject(with: data) as [String: Any] else {
            return nil
        }

        return Box(dictionary)
    }
}

you can use this like below.

struct SomeCodable: Codable {
    let foo: String
    let bar: Int
}

let object: SomeCodable = .init(foo: "foo", bar: 1)
let template = try Template(string: "your_template")
try template.render(object.mustacheObject)