Search code examples
symfonytagstwigtwig-extension

Twig how to get html between two tags to a service


I want some simple twig tags that allow me to do the following:

{% customtag 'name' %}
  <div> some html </div>
{% endcustomtag %}

And then get that html inside of a service.

I have tried doing this myself but when I finally have al the data that I want inside of my NodeVisitor I can't seem to get it to my service. If I inject it and call a method on it it never gets executed. It only gets called if I try to clear my cache from my command line.

Can somebody please give some insight?


Solution

  • Apparently, you can access your extensions from Twig_Template.

    So you can do:

    $compiler->write('$this->extensions[')
      ->string('your_extension')
      ->write(']->getService()->someFunction();')
      ->raw(PHP_EOL);
    

    in your twig node. And then in your extension you should just inject the service and return it in the getService method.