twig getSource for block

时间:2016-10-27 12:36:12

标签: twig

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

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

1 个答案:

答案 0 :(得分: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 ]));

如果您不传递模板名称,则会找到当前模板的名称

{{ 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 #}

请注意,现在不建议使用功能getSource,这就是为什么我使用getSourceContext

相关问题