JavascriptsHelper.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien.potencier@symfony-project.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\Bundle\CompatAssetsBundle\Templating\Helper;
  11. use Symfony\Component\Templating\Helper\Helper;
  12. use Symfony\Component\Templating\Helper\AssetsHelper;
  13. /**
  14. * JavascriptsHelper is a helper that manages JavaScripts.
  15. *
  16. * Usage:
  17. *
  18. * <code>
  19. * $view['javascripts']->add('foo.js');
  20. * echo $view['javascripts'];
  21. * </code>
  22. *
  23. * @author Fabien Potencier <fabien.potencier@symfony-project.com>
  24. */
  25. class JavascriptsHelper extends Helper
  26. {
  27. protected $javascripts = array();
  28. protected $assetHelper;
  29. /**
  30. * Constructor.
  31. *
  32. * @param AssetsHelper $assetHelper A AssetsHelper instance
  33. */
  34. public function __construct(AssetsHelper $assetHelper)
  35. {
  36. $this->assetHelper = $assetHelper;
  37. }
  38. /**
  39. * Adds a JavaScript file.
  40. *
  41. * @param string $javascript A JavaScript file path
  42. * @param array $attributes An array of attributes
  43. */
  44. public function add($javascript, $attributes = array())
  45. {
  46. $this->javascripts[$this->assetHelper->getUrl($javascript)] = $attributes;
  47. }
  48. /**
  49. * Returns all JavaScript files.
  50. *
  51. * @return array An array of JavaScript files to include
  52. */
  53. public function get()
  54. {
  55. return $this->javascripts;
  56. }
  57. /**
  58. * Returns HTML representation of the links to JavaScripts.
  59. *
  60. * @return string The HTML representation of the JavaScripts
  61. */
  62. public function render()
  63. {
  64. $html = '';
  65. foreach ($this->javascripts as $path => $attributes) {
  66. $atts = '';
  67. foreach ($attributes as $key => $value) {
  68. $atts .= ' '.sprintf('%s="%s"', $key, htmlspecialchars($value, ENT_QUOTES, $this->charset));
  69. }
  70. $html .= sprintf('<script type="text/javascript" src="%s"%s></script>', $path, $atts)."\n";
  71. }
  72. return $html;
  73. }
  74. /**
  75. * Returns a string representation of this helper as HTML.
  76. *
  77. * @return string The HTML representation of the JavaScripts
  78. */
  79. public function __toString()
  80. {
  81. return $this->render();
  82. }
  83. /**
  84. * Returns the canonical name of this helper.
  85. *
  86. * @return string The canonical name
  87. */
  88. public function getName()
  89. {
  90. return 'javascripts';
  91. }
  92. }