Twig 将部分模板委托给 symfony 3 服务

Twig delegate part of template to a symfony 3 service

我想将部分模板的呈现委托给控制器中的服务。

像这样

Index.html.twig

<div>
  {% include 'service.html.twig' %}
</div>
<div>
  Rest of my template
</div>

Controller.php

<?php

// some previous operations
$service->display();
// some next operations
return $this->render('index.html.twig', [
  'value'=> $myvalue
  //more
]);

Service.php

<?php
class service
{

  private $templating;

  public function __construct(\Twig_Environment $templating)
  {
    $this->templating = $templating;
  }
  function display()
  {
    $this->templating->render('service.html.twig', [
      'mytest' => 'hello include'
    ]);

  }
}

Service.html.twig

TEST var {{mytest}}

如何用树枝实现这一点?

这是一种使用 Twig 扩展来实现您的目标的方法。

创建您的扩展并通过构造函数注入您的服务

<?php

namespace App\Twig;

use App\Your\Service;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;

class AppExtension extends AbstractExtension
{
    /** @var Service*/
    private $service;

    public function __construct(Service $service)
    {
        $this->service= $service;
    }

    public function getFunctions(): array
    {
        return [
            new TwigFunction('your_function_name', [$this->service, 'display'], ['is_safe' => ['html']),
        ];
    }
}

如您所见,getFunctions 方法允许您声明自定义 twig 函数。此方法 return 一个 TwigFunction 数组。 TwigFunction class 的构造函数需要以下参数:

  • 您将在模板中使用的函数名称。
  • 当您调用该函数时将执行的可调用函数(这里是对您的服务的直接调用)
  • 第三个是可选的选项数组。在你的情况下,你必须使用它才能让你的函数 return 非转义 html.

您现在可以在模板中调用函数 "your_function_name":

<div>
  {{ your_function_name() }}
</div>
<div>
  Rest of my template
</div>