14

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?

Tomek Buszewski
  • 7,659
  • 14
  • 67
  • 112

6 Answers6

33

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')) %}
Alain Tiemblo
  • 36,099
  • 17
  • 121
  • 153
Sybio
  • 8,565
  • 3
  • 44
  • 53
  • Works great, but can you tell me, how can I check for existence of an asset? – Tomek Buszewski Jan 09 '13 at 10:00
  • I think like that: {% if file_exists(asset('images/logo.png')) %}Checked !{% endif %} because asset() returns the absolute path of the media so it can work and check the right path ^^ – Sybio Jan 09 '13 at 10:11
  • That's what I thought, but `{% if file_exists(asset('img/games/'~item.getGame.id~'.jpg')) %}` doesn't work (I mean, it returns false, even if the file is there). – Tomek Buszewski Jan 09 '13 at 10:21
  • I've just edited my answer I think I have the solution check at the end ! – Sybio Jan 09 '13 at 10:45
  • Hm, the `web_path` works great, but it still doesn't see the file. – Tomek Buszewski Jan 09 '13 at 10:51
  • Even after generating asset ? php app/console assets:install web/ Can you check if the file really exists in your server like that: cd /home/sybio/www/website/web/img/games/ or nano /home/sybio/www/website/web/img/games/3.jpg ? – Sybio Jan 09 '13 at 10:55
  • Yes, even after. And the file is there. – Tomek Buszewski Jan 09 '13 at 10:57
  • @Sybio I've tried the your method and I'm getting a `Variable "web_path" does not exist in AcmeDemoBundle:Partial:_post.html.twig at line 2` Do I need to pass this in somewhere? – esteemed.squire Jun 25 '14 at 00:02
  • @Sybio I removed web_path and it worked, however it's not finding the .jpg image. The images are located in web/images `{% if file_exists('/images/.jpg') %}` – esteemed.squire Jun 25 '14 at 00:34
  • Twig_Function_Function is deprecated use Twig_SimpleFunction instead – tom Oct 30 '15 at 08:31
  • when I've tried this solution I got Attempted to load class "FileExtension" from namespace "Esiea\BlogBundle\Twig\Extension". Did you forget a "use" statement for another namespace? can somone help me please ? – ZEE Mar 10 '16 at 21:48
  • use new \Twig_SimpleFunction('file_exists', 'file_exists'), – HMagdy Feb 25 '18 at 15:48
11

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') }}" />
Rick Pastoor
  • 3,625
  • 1
  • 21
  • 24
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.

Tobias
  • 302
  • 3
  • 4
  • I'd like to add that to add a parameter for use in twig templates you need to add it to twig config as described [here](http://stackoverflow.com/questions/6787895/how-to-get-config-parameters-in-symfony2-twig-templates) – Joe Jun 14 '13 at 17:36
1

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?

jo66
  • 79
  • 2
0

Just add a little comment to the contribution of Sybio:

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.

Daniel Guerrero
  • 184
  • 1
  • 2
  • 8
0

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;
}
Mr Sorbose
  • 777
  • 4
  • 20
  • 34