2015-02-24 86 views
2

我有一個項目使用來自不同源文件夾的資產。其中一些資產可能會覆蓋其他資產。我想引用一個樹枝模板中的資產。如果資源存在於多個源文件夾中,則應選擇第一個資源文件夾(例如,設計圖像會覆蓋模塊圖像)。我打算使用kriswallsmith/assetic包,但找不到指定多個根文件夾的方法。 我想要的是類似Twig_Loader_Filesystem::addPath但是用於資產。使用資產覆蓋資產

例子:

源文件夾:

  • assets/design(包含images/red.jpg除了其他資產)
  • assets/module(包含images/red.jpg除了其他資產)

在樹枝模板我想以參考

{% image 'images/red.jpg' %}<img src="{{ asset_url }}" />{% endimage %} 

庫現在應該選擇圖像assets/design/images/red.jpg

這可能與assetic庫? 如果我需要擴展任何類,你能給我一些指針嗎? 或者是否有另一個庫可以更好地滿足我的需求?

回答

0

好吧,我意識到如何解決我的問題:

我必須擴展AssetFactory並覆蓋parseInput方法。我想出了以下解決方案:

use Assetic\Asset\AssetInterface; 
use Assetic\Factory\AssetFactory; 

class MyAssetFactory extends AssetFactory 
{ 
    /** 
    * @var string[] 
    */ 
    private $rootFolders; 

    /** 
    * @param string[] $rootFolders 
    * @param bool $debug 
    */ 
    public function __construct($rootFolders, $debug = false) 
    { 
     if (empty($rootFolders)) { 
      throw new \Exception('there must be at least one folder'); 
     } 

     parent::__construct($rootFolders[0], $debug); 

     $this->rootFolders = $rootFolders; 
    } 

    /** 
    * @param string $input 
    * @param array $options 
    * @return AssetInterface an asset 
    */ 
    protected function parseInput($input, array $options = array()) 
    { 
     // let the parent handle references, http assets, absolute path and glob assets 
     if ('@' == $input[0] || false !== strpos($input, '://') || 0 === strpos($input, '//') || self::isAbsolutePath($input) || false !== strpos($input, '*')) { 
      return parent::parseInput($input, $options); 
     } 

     // now we have a relatve path eg js/file.js 
     // let's match it with the given rootFolders 
     $root = ''; 
     $path = $input; 
     foreach ($this->rootFolders as $root) { 
      if (file_exists($root . DIRECTORY_SEPARATOR . $input)) { 
       $path = $input; 
       $input = $root . $path; 
       break; 
      } 
     } 

     // TODO: what to do, if the asset was not found..? 

     return $this->createFileAsset($input, $root, $path, $options['vars']); 
    } 

    /** 
    * copied from AssetFactory, as it was private 
    * 
    * @param string $path 
    * @return bool 
    */ 
    private static function isAbsolutePath($path) 
    { 
     return '/' == $path[0] || '\\' == $path[0] || (3 < strlen($path) && ctype_alpha($path[0]) && $path[1] == ':' && ('\\' == $path[2] || '/' == $path[2])); 
    } 
} 

現在我可以用不同的源文件夾創建一個新工廠。

$factory = new MyAssetFactory(array('/folder/alpha/', '/folder/beta/')); 
// $factory->set some stuff 
$twig->addExtension(new AsseticExtension($factory));