renderBlock
代わりに使用しようとしましたか?
必要な最初のパラメータはブロックの名前で、2 番目のパラメータはブロックに渡される値の連想配列でなければなりません。
したがって、ブロックをレンダリングするサービスの場合は次のようになります。
サービス クラス:
<?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 );
}
}
services.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 ) }}
これは決して完全な解決策ではありませんが、私は同様のものを使用しており、機能していることが証明されています.
HTH
タム
[編集: 2016 年 4 月 - 参考: このソリューションは Symfony 2.4 プロジェクトに取り組んでいました]