Skip to content

New Localisation system, and Date formatting

Compare
Choose a tag to compare
@MatsMoll MatsMoll released this 06 May 07:56

I is now possible to use a new protocol LocalizedTemplate in order to simplify localisation. This removes the locale: \.localePath argument in 1.2.0, by using a static var localePath = \.locale. It will also provide a enum LocalizationKeys where you can store the different keys (like "footer.about.us"), and therefore making it easier when referencing this key. E.g:

localize(.missingValues)
localize(key: "missing.values") // optional

// With a context
localize(.helloWorld, with: \.helloWorldContext)
localize(.helloWorld, with: ["name" : variable(\.name)]) // Can send in a html template with bold etc.
localizeWithContext(.helloWorld) // Using the `Context` struct a long as it conforms to `Encodable`

There is also a new feature to format dates. You can formate the date with DateFormatter.Style for a more general purpose, with dateFormat: String, or send your own formatter, if this is needed.
The locale will automatically be sett if used inside a LocalizedTemplate. And therefore format the date in the most natural form.

The runtimeIf(...) is now renderIf(...).

Localisation example:

struct LocalizedView: LocalizedTemplate {

    static let localePath: KeyPath<LocalizedView.Context, String>? = \.locale

    enum LocalizationKeys: String {
        case helloWorld = "hello.world"
        case unreadMessages = "unread.messages"
    }

    /// The content needed to render LocalizationKeys.unreadMessages
    struct UnreadMessageContext: Codable {
        let number: Int
    }

    struct Context: Codable {
        let locale: String
        let description: UnreadMessageContext
        let number: Int
        let date: Date = Date()
    }

    func build() -> CompiledTemplate {
        return div.child(
            h1.child(
                localize(.helloWorld),
                small.child(
                    date(\.date, dateStyle: .medium, timeStyle: .medium)
                )
            ),
            p.child(
                localize(.unreadMessages, with: \.description)
            ),
            p.child(
                localizeWithContext(.unreadMessages)
            )
        )
    }
}

This could lead to

<!-- locale = "en", number = 1  -->
<div>
    <h1>Hello World!
        <small>May 6, 2019 at 10:24:50 AM</small>
    </h1>
    <p>You have an unread message</p>
    <p>You have an unread message</p>
</div>

<!-- locale "nb", number = 2 -->
<div>
    <h1>Hei Verden!
        <small>6. mai 2019, 10:24:50</small>
    </h1>
    <p>Du har 2 uleste meldinger.</p>
    <p>Du har 2 uleste meldinger.</p>
</div>