Symfony2:在Twig Template中包含原始文件

时间:2015-03-11 17:35:19

标签: symfony twig

我想将原始文件(user-actions.log)包含到模板中。

该文件保存在/MyBundle/Ressources/views/Admin/user-actions.log中(必要时可以更改目录)

尝试包含{{ include('MyBundle:Admin:user-actions.log) }}{% include 'MyBundle:Admin:user-actions.log' }}的文件无效,因为它不是.twig

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:3)

写一个枝条延伸

<?php
namespace Acme\AcmeBundle\Twig;

use Symfony\Component\HttpKernel\KernelInterface;

class Extension extends \Twig_Extension
{

    private $kernel;
    private $service_container;

    public function __construct(KernelInterface $kernel, $service_container)
    {
        $this->kernel = $kernel;
        $this->service_container = $service_container;
    }

        public function getFunctions()
        {
            return array(
                'includeFile'            =>  new \Twig_Function_Method($this, 'includeFile')
            );
       }

        public function includeFile($file)
        {
            return file_get_contents($file);
        }

}

在services.yml

parameters:
     acme.twig.extension.class: Acme\AcmeBundle\Twig\Extension

services:
   acme.twig.extension:
      class: %acme.twig.extension.class%
      arguments:
          kernel: "@kernel"
          service_container: "@service_container"
      tags:
        - { name: twig.extension }

在您的树枝模板中,您可以使用

{{ includeFile(your_path_to_the_file.log) }}

更多文档 http://symfony.com/doc/current/cookbook/templating/twig_extension.html