xgettext Extract Translatable Strings From Golang html/template
GNU gettext tools are great for creating i18n (web) applications. xgettext is one of GNU gettext utilities, which extracts translatable strings from given input files, and outputs PO template (POT file).
If HTML templates are written by Go html/template (read [3]), you will find that xgettext cannot extracts translatable strings directly from the templates, because Go html/template uses different syntax.
We can write a custom gettext function and use this function in templates by Go html/template (read [3]), but the gettext function must be called with the following syntax:
{{gettext "Home"}}
But xgettext can not extract above strings. The idiomatic syntax used for xgettext to extract strings are:
{{gettext("Home")}}
So how to extract the translatable strings in syntax of Go html/template? After some googling [4], I found [5] provides me the idea of solution. The solution is to uses sed to convert the Go html/template syntax to idiomatic syntax by the following command:
sed "s/{{gettext \(".*"\)}}/{{gettext(\1)}}/g" html.go | xgettext --no-wrap --language=c --from-code=UTF-8 --output=locale/messages.pot -
After conversion of syntax, the output are feeded to xgettext to extract strings. Handlebars templates uses syntax silimiar to Go html/template, so the solution here is also applied to Handlebars templates.
Tested on: Ubuntu Linux 15.10, Go 1.5.3.
References:
[1] | Internationalization (i18n) of Web Application by GNU gettext Tools |
[2] | [Golang] Internationalization (i18n) of Go Application by GNU gettext Tools |
[3] | (1, 2) i18n Golang Web Application by gettext and html/template |
[4] | xgettext example |
[5] | php - Let xgettext find keywords in comments - Stack Overflow |
[6] | gmarty/xgettext · GitHub (Extract translatable strings from Handlebars templates.) |
[7] | arendjr/grunt-xgettext: Grunt xgettext plugin for JavaScript and Handlebars |