Skip to content

Conversation

Just4Ease
Copy link

  • Allowed filter function to accept an extra parameter called bind ( this parameter is the executionContext.Public value )

  • this allows for the easy use of localization in templates see my example:

func registerTranslations() {
	localizationFilterFunction := func(in *pongo2.Value, param *pongo2.Value, bind map[string]any) (*pongo2.Value, *pongo2.Error) {
		if !in.IsString() {
			return in, nil
		}

		locale, ok := bind["locale"].(string)
		if !ok {
			locale = "en"
		}

		value, ok := translations.Load(locale)
		if !ok {
			value, ok = translations.Load("en")
		}

		localizer := value.(*i18n.Localizer)

		translatedText, err := localizer.Localize(&i18n.LocalizeConfig{
			MessageID:    in.String(),
			TemplateData: bind, // This is deliberately set to the bind variable to allow for dynamic translations based on the context of the page and the variables passed to it.
		})

		if err != nil {
			return in, nil
		}

		return pongo2.AsValue(translatedText), nil
	}

In the html:

{{ "hello_message" | translation }}

in the language files:

fr.json >

{
"hello_message": "Salut {{ .Name }}!"
}

en.json >

{
"hello_message": "Hello {{ .Name}}!"
}

@sonarqubecloud
Copy link

Quality Gate Passed Quality Gate passed

Issues
0 New issues

Measures
0 Security Hotspots
No data about Coverage
No data about Duplication

See analysis details on SonarCloud

@Just4Ease
Copy link
Author

The above example is how I currently use the library in Borderless Delivery.

I set my template tags to curly braces to make it familiar for my devs like how they do vue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant