Symfony check whether jQuery already included

本秂侑毒 提交于 2019-12-13 06:10:04

问题


Is there any way to check in sfContext whether jQuery library is already added, using:

sfContext::getInstance()->getResponse()->addJavascript('/js/jquery-1.4.2.min.js');

or

addJavascript('jquery-1.4.2.min.js', sfView::getContext());

or

use_javascript('jquery-1.4.2.min.js');

in the templates?

Seems to me that adding more jQuery's stops their action.


回答1:


You should use your own check.

  1. Use your own sfWebResponse
  2. Override addJavascript
  3. Add the check

So create a new myWebResponse.class.php file in /lib/response/ folder (create it), with this code :

class myWebResponse extends sfWebResponse 
{
  public function addJavascript($file, $position = '', $options = array())
  {
    $this->validatePosition($position);

    // check if the file to add is jquery
    // nb: you might update the regex 
    if (preg_match('/jquery/i', $file))
    {
      // retrieve all loaded js
      $files = array_keys($this->getJavascripts());

      // check if one them containt jquery
      // nb: you might update the regex 
      $isJquery = preg_grep("/jquery/i", $files);

      // jquery found so do not add the file
      if ( ! empty($isJquery))
      {
        return;
      }
    }

    $this->javascripts[$position][$file] = $options;
  }

Then, use your new response by default. In your apps/frontend/config/factories.yml, add:

all:
  response:
    class: myWebResponse 

You're done.



来源:https://stackoverflow.com/questions/10813920/symfony-check-whether-jquery-already-included

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!