Twig - Automatically insert templatename as html c

2019-07-13 11:03发布

问题:

I am working on a php project and using twig as template engine and wondering if there is a possibility to automatically add the used template filename/path into a twig template as html-comment?

That would be great for debugging, since I could have a look at the html code and find out, in which twig file I have to look, if I want to change something.

For example, the result should look like this:

<!-- start tpl/layout.twig -->
<html>
<head></head>
<body>
    <!-- start tpl/header.twig -->
    <header>My header</header>
    <!-- end tpl/layout.twig -->

    <!-- start tpl/content.twig -->
    <section>
        <!-- start tpl/article.twig -->
        <article>blabla1</article>
        <!-- end tpl/article.twig -->

        <!-- start tpl/article.twig -->
        <article>xyz</article>
        <!-- end tpl/article.twig -->
    </section>
    <!-- end tpl/content.twig -->

</body>
</html>
<!-- end tpl/layout.twig -->

回答1:

If it's not in your index view , you can have the name of template with :

{{ app.request.attributes.get('_template').get('name') }}

To get full path :

{{ app.request.attributes.get('_template')}}


标签: php twig