Giter VIP home page Giter VIP logo

lingo-vapor's Introduction

Lingo Provider

Language GitHub license

A Vapor provider for Lingo - a pure Swift localization library ready to be used in Server Side Swift projects.

Setup

Add a dependancy

Add LingoProvider as a dependancy in your Package.swift file:

dependencies: [
	...,
	.package(name: "LingoVapor", url: "https://github.com/vapor-community/Lingo-Vapor.git", from: "4.2.0")]
],
targets: [
    .target(name: "App", dependencies: [
        .product(name: "LingoVapor", package: "Lingo-Vapor")

Upgrading from version 4.1.0 to version 4.2.0

The version 4.1.0 uses the new version of Lingo where the format of locale identifiers was changed to match RFC 5646. Prior to 4.2.0 _ was used to separate language code and country code in the locale identifier, and now the library uses - as per RFC.

If you were using any locales which include a country code, you would need to rename related translation files to match the new format.

Add the Provider

In the configure.swift simply initialize the LingoVapor with a default locale:

import LingoVapor
...
public func configure(_ app: Application) throws {
	...
	app.lingoVapor.configuration = .init(defaultLocale: "en", localizationsDir: "Localizations")
}

The localizationsDir can be omitted, as the Localizations is also the default path. Note that this folder should exist under the workDir.

Use

After you have configured the provider, you can use lingoVapor service to create Lingo:

let lingo = try app.lingoVapor.lingo()
...
let localizedTitle = lingo.localize("welcome.title", locale: "en")

To get the locale of a user out of the request, you can use request.locale. This uses a language, which is in the HTTP header and which is in your available locales, if that exists. Otherwise it falls back to the default locale. Now you can use different locales dynamically:

let localizedTitle = lingo.localize("welcome.title", locale: request.locale)

When overwriting the requested locale, just write the new locale into the session, e.g. like that:

session.data["locale"] = locale

Use the following syntax for defining localizations in a JSON file:

{
	"title": "Hello Swift!",
	"greeting.message": "Hi %{full-name}!",
	"unread.messages": {
		"one": "You have one unread message.",
		"other": "You have %{count} unread messages."
	}
}

Locale redirection middleware

In case you want to serv different locales on different subfolders, you can use the LocaleRedirectMiddleware.

Add in configure.swift:

import LingoVapor

// Inside `configure(_ app: Application)`:
app.middleware.use(LocaleRedirectMiddleware())

Add in routes.swift:

import LingoVapor

// Inside `routes(_ app: Application)`:
app.get("home") { /* ... */ }
app.get(":locale", "home") { /* ... */ } // For each route, add the one prefixed by the `locale` parameter

That way, going to /home/ will redirect you to /<locale>/home/ (with <locale> corresponding to your browser locale), and going to /fr/home/ will display homepage in french whatever the browser locale is.

Inside Leaf templates

When using Leaf as templating engine, you can use LocalizeTag, LocaleTag and LocaleLinksTag from LingoVaporLeaf for localization inside the templates.

Add in configure.swift:

import LingoVaporLeaf

// Inside `configure(_ app: Application)`:
app.leaf.tags["localize"] = LocalizeTag()
app.leaf.tags["locale"] = LocaleTag()
app.leaf.tags["localeLinks"] = LocaleLinksTag()

Afterwards you can call them inside the Leaf templates:

<!-- String localization -->
#localize("thisisthelingokey")
#localize("lingokeywithvariable", "{\"foo\":\"bar\"}")

<!-- Get current locale -->
<html lang="#locale()">

<!-- Generate link canonical and alternate tags -->
#localeLinks("http://example.com/", "/canonical/path/")

Learn more

  • Lingo - learn more about the localization file format, pluralization support, and see how you can get the most out of the Lingo.

lingo-vapor's People

Contributors

abhidsm avatar calebkleveter avatar joeblau avatar jordanebelanger avatar martinlasek avatar miroslavkovac avatar nathanfallet avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

lingo-vapor's Issues

Custom vapor's working dir issue!

Vapor 4.0
macOS 10.15.6

I set vapor's working dir manual.
app.directory = DirectoryConfiguration(workingDirectory: "/some/place/i/prefer")
and then
app.lingoVapor.configuration = .init(defaultLocale: "en")

Does it support custom working dir?

error

error":true,"reason":"Error Domain=NSCocoaErrorDomain Code=260 "The folder “Localizations” doesn’t exist."

Example Project

Is there an example/demo repo I could look at to see how this is implemented?

I dont understand how you title/specify the localization .json files, nor do I understand how the middleware interacts with that.

        routes.get("hello-world") { req async throws -> String in
            let lingo = try app.lingoVapor.lingo()
            let localizedTitle = lingo.localize("title", locale: req.locale)
            return localizedTitle
        }

Screen Shot 2022-06-05 at 9 56 06 PM

2022-06-05 21:52:49.648688-0400 Run[43028:3152906] Vapor/Request+Session.swift:17: Fatal error: No `SessionsMiddleware` detected.

Issues regarding #6 and #7

Hello!
Thanks for making this Package available. It is the only package I found that allows to Localize a Vapor app.
But there are missing things, that #6 and #7 are bringing, but they are still not merged (and even outdated; I tried to implement the suggested code into a project and it gave many errors)

Any possibility to get them patched and merged?

Error in README

Hello. I found error.

targets: [
.target(name: "App", dependencies: [
.product(name: "LingoVapor", package: "LingoVapor")
-----------------------------------------^^^^^^^^

package: "LingoVapor" need fix to package: "lingo-vapor"

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.