Drupal 6: Translating user-defined (dynamic, variable) strings

There are times during Drupal module development when you want to translate a string which is defined by the user and read from the database. You are not supposed to apply the t() function in this case because it should only be used for static strings with variable (non-locale-specific) replacements. (Break this rule if you want to confuse the localization tools reponsible for extracting strings from code.)

As an example of the problem, consider Drupal's core contact.module, which at the time of writing is (regrettably) not fully localized. It allows the user to define categories, whose names are then displayed in the GUI:

Original:

    $categories[$category->cid] = $category->category;

Wrong solution:

    $categories[$category->cid] = t($category->category);

(At least partially) Correct solution:

    $categories[$category->cid] = i18nstrings_ts(
       'contact:category:' . $category->cid . ':name',
       $category->category, NULL, TRUE);

The last solution (relying on i18n.module API) is good. You will be able to find and translate the strings using the localization UI. It has a cosmetic flaw that the localization UI is not really aware of the new 'contact' textgroup, so the group name will not be displayed at all. If you want a full-fledged solution, follow instructions on making your custom data translatable and study i18ncontent.module or i18views.module for further details.

1 comment:

Unknown said...

Hi there! A better solution to translate your strings is to use a collaborative translation management platform like https://poeditor.com/. It has a simple and user-friendly work interface, and many useful features (API, GitHub integration, WordPress plugin) to simplify the localization process for developers and translators.

Post a Comment