简体   繁体   中英

How to render twig macro in controller symfony 2

i can't figure out, how to render a macro in Symfony 2 controller. This is how i can render a twig template

$this
  ->get("twig")
  ->render("AcmeBundle:Product:table.html.twig", array(
    "product" => $product
  ))
;

So i searching for something similar, but for rendering a twig macro. Thx for any suggestions!

Twig macro's are something inside a template. They are run whenever you render a template executing the macro.

Just create another "wraper" template, which would have only that macro in it. Something like

macro.html.twig file

{% macro sample(item) %}
   {# some code here #}
{% endmacro sample #}

sample_macro_wrapper.html.twig

{% from 'macro.html.twig' import sample %}
{{ sample(item) }}

controller.php

public function someAction()
{
      // ...........
      $renderedMacro = $this->get('twig')
           ->render('sample_macro_wrapper.html.twig', ['item' => $item]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM