Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?php
/**
* Twig Filter for Symfony 2 - check if asset exists.
*
* Modified Alain's Tiemblo code: http://stackoverflow.com/a/16906315/2512304
*
* Installation:
* 1. Add this file to your bundle into src/Acme/DemoBundle/Twig/AssetExistsExtension.php
* 2. Update namespace, if your bundle isn't Acme/DemoBundle
* 3. Register it in app/config.yml:
* services:
* assetexists.twig.extension:
* class: Acme\DemoBundle\Twig\AssetExistsExtension
* arguments: ['@kernel']
* tags:
* - { name: twig.extension }
* If you're using different web directiory, you should specify it as the second argument, e.g.:
* arguments: ['@kernel', 'public_html']
*
* Usage:
* {% if asset_exists('images/my_picture.jpg') %}
*/
namespace My\FrontendBundle\Twig;
use Symfony\Component\HttpKernel\KernelInterface;
class AssetExistsExtension extends \Twig_Extension {
private $kernel;
private $webDir;
public function __construct(KernelInterface $kernel, $webDir = 'web') {
$this->kernel = $kernel;
$this->webDir = $webDir;
}
public function getName() {
return 'assetexists';
}
public function getFunctions() {
return array('asset_exists' => new \Twig_Function_Method($this, 'asset_exists'));
}
public function asset_exists($path) {
$webRoot = realpath($this->kernel->getRootDir() . '/../' . $this->webDir);
$toCheck = realpath($webRoot . '/' . $path);
if (!is_file($toCheck))
return false;
// check if file is well contained in web/ directory (prevents ../ in paths)
if (strncmp($webRoot, $toCheck, strlen($webRoot)) !== 0)
return false;
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment