AssetExtension.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Bridge\Twig\Extension;
  11. use Symfony\Component\Asset\Packages;
  12. use Twig\Extension\AbstractExtension;
  13. use Twig\TwigFunction;
  14. /**
  15. * Twig extension for the Symfony Asset component.
  16. *
  17. * @author Fabien Potencier <fabien@symfony.com>
  18. */
  19. final class AssetExtension extends AbstractExtension
  20. {
  21. private $packages;
  22. public function __construct(Packages $packages)
  23. {
  24. $this->packages = $packages;
  25. }
  26. /**
  27. * {@inheritdoc}
  28. */
  29. public function getFunctions(): array
  30. {
  31. return [
  32. new TwigFunction('asset', [$this, 'getAssetUrl']),
  33. new TwigFunction('asset_version', [$this, 'getAssetVersion']),
  34. ];
  35. }
  36. /**
  37. * Returns the public url/path of an asset.
  38. *
  39. * If the package used to generate the path is an instance of
  40. * UrlPackage, you will always get a URL and not a path.
  41. */
  42. public function getAssetUrl(string $path, string $packageName = null): string
  43. {
  44. return $this->packages->getUrl($path, $packageName);
  45. }
  46. /**
  47. * Returns the version of an asset.
  48. */
  49. public function getAssetVersion(string $path, string $packageName = null): string
  50. {
  51. return $this->packages->getVersion($path, $packageName);
  52. }
  53. }