你试过renderBlock
改用吗?
您需要的第一个参数是块的名称,第二个应该是传递给块的值的关联数组。
因此,对于呈现块的服务,您将拥有以下内容:
服务等级:
<?php
namespace Acme\BlockBundle\Blocks;
use Doctrine\Common\Persistence\ObjectManager;
Class Block {
private $om;
private $environment;
private $template;
public function __construct( ObjectManager $om, Twig $environment )
{
$this->om = $om;
$this->environment = $environment;
}
public function render( $template, $data )
{
$this->template = $this->environment->loadTemplate( $template );
// maybe query the DB via doctrine, that is why I have included $om
// in the service arguments
// example:
$entities = $om->getRepository( 'AcmePizzaBundle:Pizza' )->getMeatyOnes()
return $this->template->renderBlock( 'acme_block', array(
'data' => $entities,
));
}
}
Twig 扩展类
<?php
namespace Acme\BlockBundle\Twig\Extension;
use Twig_Extension;
use Twig_Function_Method;
class BlockExtension extends Twig_Extension
{
protected $container;
public function __construct( $container )
{
$this->container = $container;
}
public function getName()
{
return 'block_extension';
}
public function getFunctions()
{
return array(
'render_block' => new Twig_Function_Method( $this, 'renderBlock', array(
'is_safe' => array( 'html' ),
)),
);
}
public function renderBlock( $template, $data )
{
return $this->container->get( 'acme.block' )->render( $template, $data );
}
}
服务.yml
parameters:
acme.blocks.block.class: Acme\BlocksBundle\Blocks\Block
acme.twig.block_extension.class: Acme\BlocksBundle\Twig\Extension\BlockExtension
services:
acme.blocks.block:
class: '%acme.blocks.block.class%'
arguments:
- '@doctrine.orm.entity_manager'
- '@twig'
acme.twig.block_extension:
class: %acme.twig.block_extension.class%
arguments:
- '@service_container'
tags:
- { name: twig.extension }
不要忘记您的模板:
{% block acme_block %}
{% spaceless %}
{# do something with your data here #}
{% endspaceless %}
{% endblock acme_block %}
然后当你想显示它时,你只需要调用你刚刚创建的twig函数:
{{ render_block( '::block_template.html.twig', someDataOneThePage ) }}
这绝不是一个完整的解决方案,但我使用了类似的东西,它被证明是有效的。
高温高压
谭
[编辑:2016 年 4 月 - 供参考:此解决方案正在处理 Symfony 2.4 项目]