mattermost / mattermost-plugin-github

GitHub plugin for Mattermost
Apache License 2.0
156 stars 146 forks source link

Base setup for i18n for server with go-i18n library #782

Open Kshitij-Katiyar opened 2 months ago

Kshitij-Katiyar commented 2 months ago

Summary

It includes: 1) Added the go-i18n library v2. 2) Added sample translation and also en.json file

Fixes https://github.com/mattermost/mattermost-plugin-github/issues/783

mickmister commented 1 month ago

In order to include localization in templates, we'll need to have the code-operated parts (i.e. markdown link construction) of the message be parameterized into the translation string. We can pass the calculated sub-template calls as a dictionary argument to the localize function

With this in i18n/en.json

{
     "newPullRequestCollapsed": "{{.RepoName}} New pull request {{.PullRequestTitle}} was opened by {{.UserName}}.",
}
func localize(bundle *i18n.Bundle, lang string) func(id string, data map[string]interface{}) string {
    return func(id string, data map[string]interface{}) string {
        localizer := i18n.NewLocalizer(bundle, lang)
        return localizer.MustLocalize(&i18n.LocalizeConfig{
            MessageID:    id,
            TemplateData: data,
        })
    }
}

Then we can change

https://github.com/mattermost/mattermost-plugin-github/blob/e958064b9d26bd23cee76d385e721c7b4e654fee/server/plugin/template.go#L207

to

{{ localize "newPullRequestCollapsed" dict "RepoName" (template "repo" .Event.GetRepo) "PullRequestTitle" (template "pullRequest" .Event.GetPullRequest) "UserName" (template "user" .Event.GetSender) }}

Or we could instead make local variables in the template like this for potentially better readability, but we'll need to implement an expose a templateToString function to return a string:

{{ $repo := templateToString "repo" .Event.GetRepo }}
{{ $pullRequest := templateToString "pullRequest" .Event.GetPullRequest }}
{{ $user := templateToString "user" .Event.GetSender }}
{{ localize "newPullRequestCollapsed" dict "RepoName" $repo "PullRequestTitle" $pullRequest "UserName" $user }}