Extract translatable strings from constants with @translation tag

Created on 10 October 2023, 12 months ago

Problem/Motivation

Very often the same string is passed to the function t() in different places of the module code, sometimes in one file, sometimes in another.

And pretty often we have a problem when trying to update a string: updating it in a single place, and forgetting to update it in other places.

As a result, we get two different strings in the translation list, instead of one! And later - three, four, etc.

A good practice to prevent this is to not repeat yourself and use constants for the translation string. So, declare the constant with a string to translate in one place, and reuse it in all places of your module as many times as you want.

But, with this approach, we will get a warning:

Only string literals should be passed to t() where possible

I tried to get rid of this warning in the issue REVERTED: Allow passing constants to t() translate function to prevent 'Only string literals should be passed to t() where possible' CS warning Fixed and almost got success with it! But it was reverted, because of missing support to catching strings from constants in the potx.

Steps to reproduce

Proposed resolution

To resolve this problem I suggest adding a new way to add strings to the translation, via @translatable tag in the phpdoc, something like this:

class SomeClass {
  /** 
   * @const Path validation rules description
   * @translatable
   */    
  public const PATH_VALIDATION_RULES = "Only numbers and characters are allowed in the string";
}

We already have something similar in plugin annotations:

/**
 * Provides an action that can save any entity.
 *
 * @Action(
 *   id = "entity:save_action",
 *   action_label = @Translation("Save"),
 *   deriver = "Drupal\Core\Action\Plugin\Action\Derivative\EntityChangedActionDeriver",
 * )
 */

So, this approach will not require executing the code to get strings for translation, just a simple parsing should be enough.

What do you think about this idea? Maybe anyone can suggest some alternatives or better ways?

Remaining tasks

User interface changes

API changes

Data model changes

Feature request
Status

Active

Version

1.0

Component

Code

Created by

🇦🇲Armenia murz Yerevan, Armenia

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Production build 0.71.5 2024