twig getSource for block

iSe*_*nne 5 twig

在twig中,您可以使用函数getSource()获取模板的源代码.

但有没有办法获取特定块的源,而不是使用{%verbatim%}(我希望模板工作,但也读取块的来源)

Dar*_*Bee 1

如果你指的是实际Twig来源,那么我给你一些东西

$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 ]));
Run Code Online (Sandbox Code Playgroud)

如果不传递模板名称,将定位当前模板

{{ 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 #}
Run Code Online (Sandbox Code Playgroud)

请注意该函数getSource现已弃用,这就是我使用的原因getSourceContext