NielsKoole NielsKoole - 3 months ago 13
Swift Question

Can I use localization directly in a mustache template?

I've checked the documentation of Vapor (web framework for Swift: http://docs.vapor.codes/) for any hints or tips to use localization in a mustache template, but I couldn't find anything.

The example project of Vapor contains an example on how to use localization, but then I have to pass all the localized texts to my mustache template which sounds like an overkill to me. This is the example:

let drop = Droplet()
drop.get("localization", String.self) { request, lang in
return try JSON([
"title": drop.localization[lang, "welcome", "title"],
"body": drop.localization[lang, "welcome", "body"]
])
}
drop.serve()


Is there someone that can point me into the right direction?

Answer

What you're trying to do would look something like this.

let drop = Droplet()

drop.get("welcome") { request in
    let lang = drop.config["app", "lang"].string ?? "en"

    return try drop.view("welcome.mustache", context: [
        "title": drop.localization[lang, "welcome", "title"],
        "body": drop.localization[lang, "welcome", "body"]
    ])
}

drop.serve()

This has lang configured in app.json like so:

{
    "lang": "es"
}

Or even using an environment variable.

{
    "lang": "$LANG"
}

Vapor doesn't have any automatic way of referencing localization values through the context as of now. You should submit a feature request for this and outline how it might work! :D

Comments