Symfony2 : use translator in a twig filter extension

标签 symfony filter translation

我正在尝试在这样的自定义 Twig 过滤器中使用翻译

public function formatTime($timestamp)
{
    $str = date('j %\m%',$timestamp);
    $str = str_replace($str, '%m%', $this->get('translator')->trans('month'.date('m', $timestamp) ) );
    return $str;
}

offcourse get 是未知功能。
我应该让我的扩展了解环境还是简单地请求翻译类以使其可用?

最佳答案

您可以注入(inject) translator服务到你的类(class):

<service id="acme.extension" class="Acme\Twig\Extensions\FormatterExtension">
    <tag name="twig.extension"/>
    <argument type="service" id="translator"/>
</service>

然后将翻译器的实例存储在 protected 字段中并稍后使用:

public function formatTime($timestamp)
{
    $str = date('j %\m%',$timestamp);
    $str = str_replace($str, '%m%', $this->translator->trans('month'.date('m', $timestamp) ) );
    return $str;
}

UPD1: YAML 服务定义的配置:
acme.extension:
    class: Acme\Twig\Extensions\FormatterExtension
    arguments: [@translator]
    tags:
        - name: twig.extension

关于Symfony2 : use translator in a twig filter extension,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11102344/

相关文章:

symfony - 使用 transchoice 和 lingohub 进行性别相关翻译

symfony - 在使用 FOSUserBundle 的用户注册期间添加默认角色

php - 可捕获的 fatal error : Object of class Proxies\__CG__\AppBundle\Entity\Modelo could not be converted to string

Angularjs过滤器不过滤精确匹配

javascript - TypeError : obj[key]. 包括不是一个函数:在过滤器函数中

Symfony 4 翻译资源最佳实践

php - Symfony 2 动态路由(例如商店)

php - 尝试从命名空间加载类 "PDO"

C++使用算法过滤类 vector

postgresql - 间隔的翻译