Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Twig getSource for block

Tags:

twig

In twig you can get the source of a template using the function getSource().

But is there a way to get the source of a specific block, and not use {% verbatim %} (I want the template to work, but also read the source of a block)

like image 264
iSenne Avatar asked Nov 08 '22 07:11

iSenne


1 Answers

If you mean the actual Twig source, then I got you something

$twig->addFunction(new Twig_SimpleFunction('get_block_source', function(\Twig_Environment $environment, $name, $template_name = null) {
        if ($template_name === null) {
            foreach (debug_backtrace() as $trace) if (isset($trace['object']) && $trace['object'] instanceof Twig_Template && 'Twig_Template' !== get_class($trace['object'])) {
                $template = $trace['object'];
                $template_name = $template->getSourceContext()->getName();
                break;
            }           
        }
        if (preg_match('#{% block '.$name.' %}(.+?){% endblock %}#is', $environment->getLoader()->getSourceContext($template_name)->getCode(), $matches)) return $matches[0];
        return 'Block not found';

}, [ 'needs_environment' => true ]));

If you don't pass the template name, the current one will be located

{{ get_block_source('bar2', 'test.html') }} {# prints block bar2 from test.html #}

{% block foo %}
    {{ 'Hello world' }}
{% endblock %}

{{ get_block_source('foo') }} {# print block foo from current template #}

do note that function getSource is now deprecated, that is why i'm using getSourceContext

like image 157
DarkBee Avatar answered Jan 04 '23 01:01

DarkBee