简体   繁体   English

ZF3 - AbstractTranslatorHelper和sprintf

[英]ZF3 - AbstractTranslatorHelper and sprintf

I have a simple view helper "Header" with two parameters title and subtitle . 我有一个简单的视图助手“标题”,有两个参数titlesubtitle My helper extends the AbstractTranslatorHelper for translating the two strings. 我的助手扩展了AbstractTranslatorHelper以翻译两个字符串。

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? 通常我会用sprintf($this->translate('My string with the variable %s', 'test')来做这个。但是如何在我的帮助器中设置字符串和变量来处理其中的翻译。或者在我设置它之前我真的需要翻译吗?

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')

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 使用此代码通过调用setTitleVariablessetSubtitleVariables您可以为这两个字符串传递变量

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 : 当然,只要你渲染一个字符串然后是下面的代码,就可以使用.phtml文件或任何你想要的东西来设计它:

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

Will do the full thing ! 会做完整的事情!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM