Skip to content

i18n: Introduce Translate component #18614

Description

@aduth

Previously: #9846, #17376

With the introduction of __experimentalCreateInterpolateElement in #17376, it is now possible to include React elements in the output result of a translated string. However, the usage can be verbose. Thus, we should consider some developer usability improvements, perhaps via the addition of a Translate component and/or Babel transform to coerce an expressed syntax to an equivalent call to __experimentalCreateInterpolateElement.

Example:

Ideally, I could express some translated string as simply as:

<Translate>Check out this link to my <a href={ url }>website</a>.</Translate>

This can be achieved today with __experimentalCreateInterpolateElement, but it would be implemented as:

__experimentalCreateInterpolateElement(
    __( 'Check out this link to my <a>website</a>.' ),
    {
        a: <a href={ url } />,
    }
)

Task:

Allow a developer to express this rendering using Translate. It could be implemented in one (or both) of two ways:

  • A Translate component which traverses its children to build up the interpolate string and conversion map.
  • A Babel transform which converts the Translate element to __experimentalCreateInterpolateElement at build-time

A "both" approach may be ideal, since it allows the component to exist and be operable even without the Babel plugin (rather than a "magic, invisible" component). In such an approach, it might be good to overload the component to accept conversionMap as a prop:

<Translate conversionMap={ { a: <a href={ url } /> } }>{ 'Check out this link to my <a>website</a>.' }</Translate>

It wouldn't be expected that a developer would ever literally write this element rendering in source, but rather that it would be the produced output from a Babel transform.

Considerations:

  • String extraction must be preserved (reference)
  • Consider how plugin "domain" fits (reference)

References:

Some prior art of Babel transforms in Gutenberg:

Babel plugin handbook: https://github.com/jamiebuilds/babel-handbook/blob/master/translations/en/plugin-handbook.md

AST Explorer is an invaluable tool to use as a reference for implementing AST node visitors:

cc @nerrad

Metadata

Metadata

Assignees

No one assigned

    Labels

    Internationalization (i18n)Issues or PRs related to internationalization effortsNeeds DevReady for, and needs developer efforts[Package] Components/packages/components[Type] TaskIssues or PRs that have been broken down into an individual action to take

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions