Symfony2 - checking if file exists

前端 未结 6 1241
执笔经年
执笔经年 2020-12-05 05:59

I have a loop in Twig template, which returns multiple values. Most important - an ID of my entry. When I didn\'t use any framework nor template engine, I used simply

6条回答
  •  Happy的楠姐
    2020-12-05 06:06

    Here is my solution, using SF4, autowire and autoconfigure:

    namespace App\Twig;
    
    use Twig\Extension\AbstractExtension;
    use Twig\TwigFunction;
    use Symfony\Component\Filesystem\Filesystem;
    
    class FileExistsExtension extends AbstractExtension
    {
        private $fileSystem;
        private $projectDir;
    
        public function __construct(Filesystem $fileSystem, string $projectDir)
        {
            $this->fileSystem = $fileSystem;
            $this->projectDir = $projectDir;
        }
    
        public function getFunctions(): array
        {
            return [
                new TwigFunction('file_exists', [$this, 'fileExists']),
            ];
        }
    
        /**
         * @param string An absolute or relative to public folder path
         * 
         * @return bool True if file exists, false otherwise
         */
        public function fileExists(string $path): bool
        {
            if (!$this->fileSystem->isAbsolutePath($path)) {
                $path = "{$this->projectDir}/public/{$path}";
            }
    
            return $this->fileSystem->exists($path);
        }
    }
    

    In services.yaml:

    services:
        App\Twig\FileExistsExtension:
            $projectDir: '%kernel.project_dir%'
    

    In templates:

    # Absolute path
    {% if file_exists('/tmp') %}
    # Relative to public folder path
    {% if file_exists('tmp') %}
    

    I am new to Symfony so every comments are welcome!

    Also, as initial question is about Symfony 2, maybe my answer is not relevant and I would better ask a new question and answer by myself?

提交回复
热议问题