Search code examples
phpzend-framework2zend-framework3

ZF3 - AbstractTranslatorHelper and sprintf


I have a simple view helper "Header" with two parameters title and subtitle. My helper extends the AbstractTranslatorHelper for translating the two strings.

Now I have the case, that I have to set some variables in the given string. Normally I would do this with sprintf($this->translate('My string with the variable %s', 'test'). But how can I set the string and the variables in my helper, to handle the translation in it. Or do I really have to translate it before I set it?

At the moment I do it that way, but I don't really like it...

$this->header(sprintf($this->translate('title with variable %s'), 'test'), 'subtitle')

Solution

  • you can do this

    $this->header('title with variable %s', 'subtitle')->setTitleVariables([$variables])->setSubtitleVariables([$subVars]);
    

    where your main code for this to work is :

    class HeaderHelper extends AbstractTranslatorHelper
    {
        public function __invoke($title, $subtitle)
        {
            $this->title = $title;
            $this->subtitle = $subtitle;
    
            return $this;
        }
    
        public function setTitleVariables(array $variables)
        {
            $this->title = $this->translate(vsprintf($this->title, $variables));
            return $this;
        }
    
        public function setSubtitleVariables( array $variables)
        {
            $this->subtitle = $this->translate(vsprintf($this->subtitle, $variables));
            return $this;
        }
    }
    

    With this code by calling either setTitleVariables or setSubtitleVariables you can pass variable for those two strings

    Then, up to you with your populated helper to choose how to render those strings.

    But I suggest you this method :

     public function render()
        {
            return "<h1>" . $this->title . "</h1>" . "<h3>" . $this->subtitle . "</h3>";
        }
    

    Of course you can design this by using a .phtml file or anything you want as long as you render a string and then the code below :

    $this->header('title with variable %s', 'subtitle')->setTitleVariables([$variables])->render();
    

    Will do the full thing !