Search code examples
javascriptvue.jsgettextxgettext

Using xgettext to extract translatable strings from VueJS file


I am trying to use xgettext to extract strings to be translated from a VueJS file. I am not able to get xgettext to recognize JS that is in a VueJS computed property though.

For example, I have an element in my <template> like so:

<input :placeholder="translator.gettext('Phone')" />

This fails to get picked up when running xgettext like so:

xgettext --from-code=UTF-8 --language=JavaScript

But if I have a translatable string as a function call, it is picked up. For example:

<div>{{ translator.gettext('This is picked up 1') }}</div>
<input :placeholder="translator.gettext('This is NOT picked up')" />
<div>{{ translator.gettext('This is picked up 2') }}</div>

The input placeholder is not picked up, but the other 2 strings are.

I believe this is because xgettext considers anything inside an html property to be just a string, but VueJS will run any value in a property prefixed by a : as pure JavaScript.

Is there any way to get xgettext to understand that this code is JS and not just a string?


Solution

  • I think translation does not work on attributes. Maybe you can try using a computed property to achieve this like:

    computed: {
       placeholderText () {
         return this.translator.gettext('This is a text')
       },
    },
    

    and then use this computed property in your template like:

    <input :placeholder="placeholderText" />
    

    Or, you can create a filter for this like:

    Vue.filter('translate', value => {
      return !value ? '' : Vue.prototype.translator.gettext(value.toString())
    })
    

    and then use it like:

    <input :placeholder="'This is a text' | translate" />