【问题标题】:How to display global variable in twig?如何在树枝中显示全局变量?
【发布时间】:2018-05-14 16:56:52
【问题描述】:

控制器

$count_em =  $this->getDoctrine()->getRepository('AppBundle:St_Jude_Email');
    $count_dql = $count_em->createQueryBuilder('c')
            ->select('count(c.flag)')
            ->where('c.flag = 0');
    $flag_count = $count_dql->getQuery();
    $count = $flag_count->getSingleScalarResult();

    return $count;

Config.yml

 Twig:
  globals:  
    count: '@AppBundle\Controller\countMail'

如何在树枝中显示全局计数? 对不起,我是 symfony 的新手,不知道如何在 twig 中显示“计数”。 我尝试做 {{ count }} ,但得到错误'在模板的呈现过程中引发了异常(“可捕获的致命错误:类 AppBundle\Controller\countMail 的对象无法转换为字符串”)。'

【问题讨论】:

    标签: symfony symfony-forms symfony-3.3 symfony-3.1 twig-extension


    【解决方案1】:

    您应该创建一个服务,例如MailService,例如countAllMail() 方法。在这种方法中,您可以做您的数据库工作。之后,您可以执行以下操作:

    config.yml

    twig:
        globals:
            my_global_mail_service: '@AppBundle\Service\MailService'
    

    在您的 twig 模板中,您可以像这样使用您的服务

    {{ my_global_mail_service.countAllMail() }}
    

    【讨论】:

      【解决方案2】:

      @AppBundle\Controller\countMail - 这是一个服务引用。 在您的情况下,您需要创建一个 symfony 服务 - https://symfony.com/doc/current/service_container.html 然后将该服务作为全局 twig var 引用。 然后在您的模板中,您可以引用服务中的任何公共方法 例如 {{ count.methodThat ReturnsSomeValue }}

      使用这种方法,您无需在每个控制器操作中向树枝渲染器传递任何内容

      【讨论】:

        【解决方案3】:

        如果您需要将其返回到 Template - 将其作为数组返回。

        return ['count' => $count];
        

        在其他情况下,如果需要全局使用,则需要使用 twig 扩展,look this documentation。

        【讨论】:

        • 这不是 twig 的全局变量
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-05-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-03-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多