Symfony2 - checking if file exists

匿名 (未验证) 提交于 2019-12-03 02:14:01

问题:

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 file_exists() within the loop. Now, I can't seem to find a way to do it in Twig.

When I display user's avatar in header, I use file_exists() in controller, but I do it because I don't have a loop.

I tried defined in Twig, but it doesn't help me. Any ideas?

回答1:

If you want want to check the existence of a file which is not a twig template (so defined can't work), create a TwigExtension service and add file_exists() function to twig:

src/AppBundle/Twig/Extension/TwigExtension.php

<?php  namespace AppBundle\Twig\Extension;  class FileExtension extends \Twig_Extension {      /**      * Return the functions registered as twig extensions      *       * @return array      */     public function getFunctions()     {         return array(             new Twig_SimpleFunction('file_exists', 'file_exists'),         );     }      public function getName()     {         return 'app_file';     } } ?> 

Register your service:

src/AppBundle/Resources/config/services.yml

# ...  parameters:      app.file.twig.extension.class: AppBundle\Twig\Extension\FileExtension  services:      app.file.twig.extension:         class: %app.file.twig.extension.class%         tags:             - { name: twig.extension } 

That's it, now you are able to use file_exists() inside a twig template ;)

Some template.twig:

{% if file_exists('/home/sybio/www/website/picture.jpg') %}     The picture exists ! {% else %}     Nope, Chuck testa ! {% endif %} 

EDIT to answer your comment:

To use file_exists(), you need to specify the absolute path of the file, so you need the web directory absolute path, to do this give access to the webpath in your twig templates app/config/config.yml:

# ...  twig:     globals:         web_path: %web_path%  parameters:     web_path: %kernel.root_dir%/../web 

Now you can get the full physical path to the file inside a twig template:

{# Display: /home/sybio/www/website/web/img/games/3.jpg #} {{ web_path~asset('img/games/'~item.getGame.id~'.jpg') }} 

So you'll be able to check if the file exists:

{% if file_exists(web_path~asset('img/games/'~item.getGame.id~'.jpg')) %} 


回答2:

I've created a Twig function which is an extension of the answers I have found on this topic. My asset_if function takes two parameters: the first one is the path for the asset to display. The second parameter is the fallback asset, if the first asset does not exist.

Create your extension file:

src/Showdates/FrontendBundle/Twig/Extension/ConditionalAssetExtension.php:

<?php  namespace Showdates\FrontendBundle\Twig\Extension;  use Symfony\Component\DependencyInjection\ContainerInterface;  class ConditionalAssetExtension extends \Twig_Extension {     private $container;      public function __construct(ContainerInterface $container)     {         $this->container = $container;     }      /**      * Returns a list of functions to add to the existing list.      *      * @return array An array of functions      */     public function getFunctions()     {         return array(             'asset_if' => new \Twig_Function_Method($this, 'asset_if'),         );     }      /**      * Get the path to an asset. If it does not exist, return the path to the      * fallback path.      *       * @param string $path the path to the asset to display      * @param string $fallbackPath the path to the asset to return in case asset $path does not exist      * @return string path      */     public function asset_if($path, $fallbackPath)     {         // Define the path to look for         $pathToCheck = realpath($this->container->get('kernel')->getRootDir() . '/../web/') . '/' . $path;          // If the path does not exist, return the fallback image         if (!file_exists($pathToCheck))         {             return $this->container->get('templating.helper.assets')->getUrl($fallbackPath);         }          // Return the real image         return $this->container->get('templating.helper.assets')->getUrl($path);     }      /**      * Returns the name of the extension.      *      * @return string The extension name      */     public function getName()     {        return 'asset_if';     } } 

Register your service (app/config/config.yml or src/App/YourBundle/Resources/services.yml):

services:     showdates.twig.asset_if_extension:         class: Showdates\FrontendBundle\Twig\Extension\ConditionalAssetExtension         arguments: ['@service_container']         tags:           - { name: twig.extension } 

Now use it in your templates like this:

<img src="{{ asset_if('some/path/avatar_' ~ app.user.id, 'assets/default_avatar.png') }}" /> 


回答3:

I've had the same problem as Tomek. I've used Sybio's solution and made the following changes:

  1. app/config.yml => add "/" at the end of web_path

    parameters:     web_path: %kernel.root_dir%/../web/ 
  2. Call file_exists without "asset" :

    {% if file_exists(web_path ~ 'img/games/'~item.getGame.id~'.jpg') %} 

Hope this helps.



回答4:

Just add a little comment to the contribution of Silvio:

The Twig_Function_Function class is deprecated since version 1.12 and will be removed in 2.0. Use Twig_SimpleFunction instead.

We must change the class Twig_Function_Function by Twig_SimpleFunction:

<?php  namespace Gooandgoo\CoreBundle\Services\Extension;  class TwigExtension extends \Twig_Extension {      /**      * Return the functions registered as twig extensions      *      * @return array      */     public function getFunctions()     {         return array(             #'file_exists' => new \Twig_Function_Function('file_exists'), // Old class             'file_exists' => new \Twig_SimpleFunction('file_exists', 'file_exists'), // New class         );     }      public function getName()     {         return 'twig_extension';     } } 

The rest of code still works exactly as said Sybio.



回答5:

Improving on Sybio's answer, Twig_simple_function did not exist for my version and nothing here works for external images for example. So my File extension file is like this:

namespace AppBundle\Twig\Extension;  class FileExtension extends \Twig_Extension { /**  * {@inheritdoc}  */  public function getName() {     return 'file'; }  public function getFunctions() {     return array(         new \Twig_Function('checkUrl', array($this, 'checkUrl')),     ); }  public function checkUrl($url) {     $headers=get_headers($url);     return stripos($headers[0], "200 OK")?true:false; } 


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!