Search code examples
zend-frameworkzend-translateplural

Can you inject variables into the text when using Zend_Translate in plural mode


I'm trying to use Zend_translate in a situation where I have to inject a variable value into the resulting string and have the string respect plural form. Using the regular (non-plural) view helper $this->translate() in a view script I can inject a variable into the string:

$this->translate('You have %1$s questions to answer', 3) 
// would result in "You have 3 questions to answer" being output

But how do I do this when using what Zend calls the modern way of plural notation? Apparently the $this->translate() view helper itself does not support the plural notation, instead I have to call

$this->translate()->getTranslator()->translate( 
    array('You have %1$s question to answer', 
    'You have %1$s questions to answer', $someNr ) 
)

But at that point I only have the plural string with the variable placeholder, I don't have the string with an injected value. In other words, what I'm getting is:

You have %1$s questions to answer

What I want is

You have 2 questions to answer

So the question is, does Zend_Translate somehow support this way of using plural? I.e. inject a variable value into the pluralized string? Or do I have to go with splitting up the string before and after the plural form, translate each separately and then concatenate at output?


Solution

  • In the controller (or elsewhere):

    <?php
            $translate = new Zend_Translate (array (
                'adapter' => 'Zend_Translate_Adapter_Array',
                'content' => array (
                    'test' => 'You have %1$s %2$s to answer'
                ),
                'locale' => 'en'
            ));
    

    In the view:

    <?php
    $x = 1;
    echo $this->translate ('test', $x, $this->translate (array (
        'question', 
        'questions', 
        $x 
    )));
    ?>
    

    But you probably want to have a look at http://framework.zend.com/manual/en/zend.translate.plurals.html for a more intelligent way to do this.