Go i18n printer directly in templates?

122 views
Skip to first unread message

Marc Coquand

unread,
Nov 21, 2024, 3:14:46 PMNov 21
to golan...@googlegroups.com

Hi!

I am trying to more easily add text into my go html templates, that I
can translate at a later stage.

So I tried adding the following in my handler

```go
p := i18nPrinter(c) // *message.Printer, uses golang's i18n library
c.HTML(http.StatusOK, "my-template.tmpl", gin.H{
"p": p,
})
```

And then within my-template, I do the following to print a specific string.

```gohtml
<p>{{ .p.Sprintf "Hello world" }}</p>
```

And then to generate translations:

```sh
$ go generate i18n/i18n.go
```

I would expect "Hello world" to show up as a list of items that need
translations, however, it seems not to.

It'd be nice if I could add the Sprintf statements directly within the
go templates, as that would lower the indirection needed.

Is there a way to accomplish that? Or is it unsupported?

Sincerely,
--
Marc

Howard C. Shaw III

unread,
Dec 9, 2024, 11:59:26 AMDec 9
to golang-nuts
The x packages parse the .go files and work on the parsed tree of a specified package - so they see only what is visible at the go compiler level, and never see what is in templates that are outside of the go files.

Here is a StackOverflow on this topic, which suggests a library that does support extraction from templates.

Here is the library recommended in that question: 
https://github.com/vorlif/spreak

Here is the relevant bullet point from the Readme:
  • Powerful extractor for strings to simplify the localization process (with support for templates)
Hope that helps,
Howard
Reply all
Reply to author
Forward
0 new messages