Including a non-twig file from twig

前端 未结 4 1801
粉色の甜心
粉色の甜心 2021-02-14 19:51

I need to include the contents of a file (inside my resources folder) inside a Twig template.

I have tried this with no luck:

{% include \'public/directo         


        
4条回答
  •  梦谈多话
    2021-02-14 20:36

    Twig will complain when loading your file if it is not a valid twig template. The reason is that Twig will include the rendered file and not the content of it (found here).

    You could try with a use statement but I don't think this will work either.

    Moreover, the syntax you use seems incorrect. When I include (or use) another twig template, I use this syntax:

    {% use "AcmeWebsiteBundle::include.html.twig" %}
    

    And the file include.html.twig resideds in src\Acme\WebsiteBundle\Resources\views\include.html.twig. So, if your file is in src\Acme\WebsiteBundle\Resources\public\directory\include.ext, you could try

    {% use "AcmeWebsiteBundle::..\public\directory\include.ext" %}
    

    If that doesn't work, you could possibly move the file into the views folder. If this is not possible, you can possibliy put in app\Resources\views\ and use the syntax:

    {% use "::include.ext" %}
    

    If the use statement doesn't work, which I'm afraid of, you could possibly wrap your file into a twig template directly. I'm templating some simple JSON structures with twig. So, there may be a way for you to include the content of file.ext into a twig template and then render it.

    If all this fail, you will have to create a Twig extension that add a new tag (something like content) that would read a file and output its content in your twig template.

    {% content 'public/directory/file.ext' %} {# would put content of the file #}
    

    Hope this will help you to include your file.

    Regards,
    Matt

提交回复
热议问题