AssetExtension.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. 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()
  30. {
  31. return array(
  32. new TwigFunction('asset', array($this, 'getAssetUrl')),
  33. new TwigFunction('asset_version', array($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. * @param string $path A public path
  43. * @param string $packageName The name of the asset package to use
  44. *
  45. * @return string The public path of the asset
  46. */
  47. public function getAssetUrl($path, $packageName = null)
  48. {
  49. return $this->packages->getUrl($path, $packageName);
  50. }
  51. /**
  52. * Returns the version of an asset.
  53. *
  54. * @param string $path A public path
  55. * @param string $packageName The name of the asset package to use
  56. *
  57. * @return string The asset version
  58. */
  59. public function getAssetVersion($path, $packageName = null)
  60. {
  61. return $this->packages->getVersion($path, $packageName);
  62. }
  63. /**
  64. * Returns the name of the extension.
  65. *
  66. * @return string The extension name
  67. */
  68. public function getName()
  69. {
  70. return 'asset';
  71. }
  72. }