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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With