Skip to content

Commit

Permalink
Update docs/en/topics/i18n.md
Browse files Browse the repository at this point in the history
Make the documentation more clear and 3.x specific. Especially around template translations.
  • Loading branch information
drzax committed Jan 9, 2013
1 parent 2ace1de commit f6ab5a4
Showing 1 changed file with 39 additions and 76 deletions.
115 changes: 39 additions & 76 deletions docs/en/topics/i18n.md
Expand Up @@ -79,7 +79,7 @@ not PHP's built-in [date()](http://nz.php.net/manual/en/function.date.php).

By default, URLs for pages in SilverStripe (the `SiteTree->URLSegment` property)
are automatically reduced to the allowed allowed subset of ASCII characters.
If characters outside this subsetare added, they are either removed or (if possible) "transliterated".
If characters outside this subset are added, they are either removed or (if possible) "transliterated".
This describes the process of converting from one character set to another
while keeping characters recognizeable. For example, vowels with french accents
are replaced with their base characters, `pâté` becomes `pate`.
Expand All @@ -103,7 +103,7 @@ Defaults can be applied globally for all field instances through [api:DateField:
and [api:TimeField::set_default_config()]. If no 'locale' default is set on the field, [api:i18n::get_locale()]
will be used.

Important: Form fields in the CMS are automatically configured according to the profile settings for the logged-in user (`Member->Locale`, `Member->DateFormat` and `Member->TimeFormat`). This means that in most cases,
**Important:** Form fields in the CMS are automatically configured according to the profile settings for the logged-in user (`Member->Locale`, `Member->DateFormat` and `Member->TimeFormat`). This means that in most cases,
fields created through [api:DataObject::getCMSFields()] will get their i18n settings from a specific member

The [api:DateField] API can be enhanced by JavaScript, and comes with
Expand All @@ -130,12 +130,12 @@ language-dependent and use a translator function call instead.
echo _t("Namespace.Entity","This is a string");


All strings passed through the `_t()` function will be collected in a separate language table (see "Collecting entities"
below), which is the starting point for translations.
All strings passed through the `_t()` function will be collected in a separate language table (see [Collecting text](#collecting-text)), which is the starting point for translations.

### The _t() function

The `_t()` function is the main gateway to localized text, and takes four parameters, all but the first being optional.
The `_t()` function is the main gateway to localized text, and takes four parameters, all but the first being optional.
It can be used to translate strings in both PHP files and template files. The usage for each case is described below.

* **$entity:** Unique identifier, composed by a namespace and an entity name, with a dot separating them. Both are arbitrary names, although by convention we use the name of the containing class or template. Use this identifier to reference the same translation elsewhere in your code.
* **$string:** (optional) The original language string to be translated. Only needs to be declared once, and gets picked up the [text collector](#collecting-text).
Expand All @@ -144,63 +144,45 @@ are very context dependent. This parameter allows the developer to convey this i
to the translator.
* **$array::** (optional) An array of injecting variables into the second parameter

#### Usage in PHP Files

:::php
//Example 4: Using context to hint information about a parameter

// Simple string translation
_t('LeftAndMain.FILESIMAGES','Files & Images');

// Using the natural languate comment parameter to supply additional context information to translators
_t('LeftAndMain.HELLO','Site content','Menu title');

// Using injection to add variables into the translated strings.
_t('CMSMain.RESTORED',
"Restored {value} successfully",
'This is a message when restoring a broken part of the CMS',
array('value' => $itemRestored)
);

### Usage

There're two types of files in a module where you can use this _t() function: code files (under code folder) and
template files (under templates)

* In code files, in order to ask for a translated string, we have to write a normal php call to this function.

Example:

:::php
_t('LeftAndMain.HELLO','Site content',PR_HIGH,'Menu title');
_t('LeftAndMain.FILESIMAGES','Files & Images',PR_HIGH);
_t('LeftAndMain.NEWSLETTERS','Newsletters');
#### Usage in Template Files

<div class="hint" markdown='1'>
The preferred template syntax has changed somewhat since [version 2.x](http://doc.silverstripe.org/framework/en/2.4/topics/i18n#usage-2).
</div>

* In template files these calls are written slightly different to ease readibility, diminish overhead and allow a
cleaner template file. Calls can be placed anywhere, but they are preceded and followed by `<% and %>` as usual in the
SilverStripe templating language, and the first parameter is omitted (namespace in template files is always the file
itself).
In `.ss` template files, instead of `_t(params)` the syntax `<%t params %>` is used. The syntax for passing parameters to the function is quite different to
the PHP version of the function.

Therefore, the following would be a valid use in templates:
* Parameters are space separated, not comma separated
* The original language string and the natural language comment parameters are separated by ` on `.
* The final parameter (which is an array in PHP) is passed as a space separated list of key/value pairs.

:::ss
<a href="http://www.silverstripe.com" title="<% _t('VISIT','Visit www.silverstripe.com') %>">


Using SS templating variables in the translatable string (e.g. $Author, $Date..) is not currently supported.

### Injection Support

Variable injection in `_t()` allows us to dynamically replace parts of a translated string, e.g. by a username or a page-title. The named parameters also allow flexible ordering of placeholders,
which might vary depending on the used language.

:::php
// in PHP-file
_t(
'CMSMain.RESTORED',
"Restored {title} successfully"),
array('title' => $title)
);

:::php
// in SS-template ($Name must be available in the current template-scope)
<%t MYPROJECT.INJECTIONS "Hello {name} {greeting}" name=$Name greeting="good to see you" %>

Note that you can still use `sprintf()` wrapped around a `_t()` call
for your substitutions. In contrast to `sprintf()`, our API has a more translator friendly
placeholder syntax, as well as more graceful fallback if not all placeholders are found
(an outdated translation with less placeholders will throw a notice rather than a fatal error).
// Simple string translation
<%t Namespace.Entity "String to translate" %>

// Using the natural languate comment parameter to supply additional context information to translators
<%t SearchResults.NoResult "There are no results matching your query." is "A message displayed to users when the search produces no results." %>

// Using injection to add variables into the translated strings (note that $Name and $Greeting must be available in the current template scope).
<%t Header.Greeting "Hello {name} {greeting}" name=$Name greeting=$Greeting %>

## Collecting text

Expand All @@ -215,11 +197,11 @@ If you want to run the text collector for just one module you can use the 'modul

`http://<mysite>/dev/tasks/i18nTextCollectorTask/?module=cms`

<div class="notice" markdown='1'>
**Note**: You'll need to install PHPUnit to run the text collector (see [testing-guide](/topics/testing)).
<div class="hint" markdown='1'>
You'll need to install PHPUnit to run the text collector (see [testing-guide](/topics/testing)).
</div>

## Language definitions (3.x)
## Language definitions

Each module can have one language table per locale, stored by convention in the `lang/` subfolder.
The translation is powered by `[Zend_Translate](http://framework.zend.com/manual/en/zend.translate.html)`,
Expand Down Expand Up @@ -247,30 +229,11 @@ Note that translations are cached across requests.
The cache can be cleared through the `?flush=1` query parameter,
or explicitly through `Zend_Translate::getCache()->clean(Zend_Cache::CLEANING_MODE_ALL)`.

## Language definitions (2.x)

In SilverStripe 2.x, the tables are just PHP files with array notations,
stored based on their locale name (e.g. "en_US.php").

Example: framework/lang/en_US.php (extract)

:::php
// ...
$lang['en_US']['ImageUploader']['ATTACH'] = array(
'Attach %s',
'Attach image/file'
);
$lang['en_US']['UploadField']['NOTEADDFILES'] = 'You can add files once you have saved for the first time.';
// ...


Translation table: framework/lang/de_DE.php (extract)

:::php
$lang['de_DE']['ImageUploader']['ATTACH'] = '%s anhängen';
$lang['de_DE']['UploadField']['NOTEADDFILES'] = 'Sie können Dateien hinzufügen sobald Sie das erste mal gespeichert haben';
<div class="hint" markdown='1'>
The format of language definitions has changed significantly in since version 2.x.
</div>

In order to enable usage of PHP language definitions in 3.x, you need to register a legacy adapter
In order to enable usage of [version 2.x style language definitions](http://doc.silverstripe.org/framework/en/2.4/topics/i18n#language-tables-in-php) in 3.x, you need to register a legacy adapter
in your `mysite/_config.php`:

:::php
Expand Down

0 comments on commit f6ab5a4

Please sign in to comment.