Symfony中的getContainer方法

6
我正在尝试从twig模板中获取一个块,并将其呈现到我的索引模板中:
{% block round1 %}
<h1> hello this is a sample for a round 1</h1>
{% endblock %}

{% block round2 %}
<h1> hello this is a sample for a round 1</h1>
{% endblock %}

然后使用以下方式将其传递到我的控制器

  use Symfony\Bundle\FrameworkBundle\Controller\Controller;
  use Alvin\MainBundle\Entity\User;
  use Symfony\Component\HttpFoundation\Request;
  use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
  use Alvin\MainBundle\Form\Type\ResetPasswordType;

 
  $templateContent = $this->getContainer()->get('twig')->loadTemplate('AngpaoMainBundle:Dynamic:dynamic.html.twig');
  $bodydynamics = $templateContent->renderBlock('round1');

然后在我的索引模板中使用它。

{{dynamic}}

但是我遇到了一个问题,Symfony 提示

FatalErrorException: Error: Call to undefined method 
Alvin\MainBundle\Controller\IndexController::getContainer() in /Users/alvinvaldez/Sites/alvinwebsite/src/Alvin/MainBundle/Controller/IndexController.php line 26

我不知道该使用什么来运行容器。
1个回答

11

控制器没有getContainer()方法。

您可以直接通过$this->container访问它,如$this->container->get('twig')

但Symfony为控制器提供了快捷方式,您也可以使用$this->get('twig')


是的,但是出现了一个新问题:Catchable Fatal Error: Argument 2 passed to Twig_Template::renderBlock() must be of the type array。 - Aoi
@Aoi 是的,你应该将一个数组作为参数提供。 - xdazz
是的,我只是传递了一个空数组,就像这样 $bodydynamics = $templateContent->renderBlock('round1', array()); 但是在我的索引模板中,动态内容会显示为:<div class="top-black-border"></div> " <h1>你好,这是第一轮的示例</h1>" - Aoi
我找到了一个答案:{{ dynamic | raw }}。 - Aoi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接