templatessymfonytwig

How do I include raw HTML files in Symfony2/Twig templates?


I'm working on a project in Symfony2 and I have several small pieces of html that need to be included in one of my main views. According to the official Twig documentation I should be able to simply use {% include 'filename.html' %} but in Symfony unless the filename ends in ".html.twig" it throws and error saying it cannot find the file. I'd like to avoid using Twig templates for these files since they have no dynamic content and lots of double braces (they're javascript templates) and requiring the template designer to have to wrap every one of these files in {% raw %} tags seems like a really Kludgey way to do it.


Solution

  • A quick recap on twig file extensions (taken from the documentation):

    Every template name also has two extensions that specify the format and engine for that template.

    AcmeBlogBundle:Blog:index.html.twig - HTML format, Twig engine
    AcmeBlogBundle:Blog:index.html.php - HTML format, PHP engine
    AcmeBlogBundle:Blog:index.css.twig - CSS format, Twig engine
    

    By default, any Symfony2 template can be written in either Twig or PHP, and the last part of the extension (e.g. .twig or .php) specifies which of these two engines should be used. The first part of the extension, (e.g. .html, .css, etc) is the final format that the template will generate.

    Therefore it makes sense to me that including a file as .html would be at the least ambiguous even if it didn't throw an error.

    So you have 3 choices:

    1. If the files are purely javascript then include them as script tags in your page.

    2. If they are mixed HTML and JS then escape the JS with {% raw %} and include the files as foo.html.twig templates. If there are lots of scripts being included like this then most likely your designers could do with a little refactoring and move the bulk of their scripts to external files (see option 1)

    3. If you really insist you could always write a Twig extension to include raw HTML files. (EDIT: See @Haprog's answer below for more details on this option).

      {{ include_html('foo/bar.html') }}

    4. UPDATE 2015 twig has since added the source function:

    {{ source('AcmeSomeBundle:Default:somefile.html.twig') }}

    Kudos to @user1850421 in the comments below for option 4.