Yiiでcssファイルとjsファイルを自動的に接続する

良い一日。



今回は、Yiiでcssファイルとjsファイルを自動的に接続する方法について説明します。 アイデアは、リソース(css、js、images)を持つ対応するフォルダーをフォームの各ファイルに添付することです。 これは便利です ほとんどの場合、特定の「ファイル」は特定のビューファイルに使用されます。



そして、コードにより近い。 Controllerクラス(おそらく「コンポーネント」フォルダーにあると思われます)を展開し、次の機能を追加します。



/** * Array of paths of assets * @var array */ private $_assetsPaths = array(); /** * Array of asset Url * @var array */ private $_assetsUrl = array(); /** * Name of directory for css files * @var strign */ protected $_cssDirName = 'css'; /** * Default file name of css * @var string */ protected $_defaultCssFile = 'index.css'; /** * Name of directory for script files * @var strign */ protected $_scriptDirName = 'js'; /** * Default file name of script * @var string */ protected $_defaultScriptFile = 'index.js'; /** * Name of directory for images * @var strign */ protected $_imageDirName = 'images'; /** * This method is invoked at the beginning of {@link render()}. * * @param string $view the view to be rendered * @return boolean whether the view should be rendered. */ protected function beforeRender($view) { $this->_setupScript($view); $this->_setupCss($view); $viewCamelCase = preg_replace_callback( '/_([a-z0-9])/', function ($char) { return strtoupper($char[1]); }, ucfirst($view) ); $methodScript = '_setupScript' . $viewCamelCase; if (method_exists($this, $methodScript)) { $this->$methodScript($view); } $methodCss = '_setupCss' . $viewCamelCase; if (method_exists($this, $methodCss)) { $this->$methodCss($view); } return true; } /** * Setup script files * * @param string $view * @return void */ protected function _setupScript($view) { $scriptRealPath = $this->getScriptPath($view, $this->_defaultScriptFile); if (is_file($scriptRealPath)) { $scriptPublishedUrl = $this->getScriptUrl($view, $this->_defaultScriptFile); Yii::app()->clientScript->registerScriptFile($scriptPublishedUrl); } } /** * Setup css files * * @param string $view * @return void */ protected function _setupCss($view) { $cssRealPath = $this->getCssPath($view, $this->_defaultCssFile); if (is_file($cssRealPath)) { $cssPublishedUrl = $this->getCssUrl($view, $this->_defaultCssFile); Yii::app()->clientScript->registerCssFile($cssPublishedUrl); } } /** * Returns the published script URL * * @param string $view * @param string $fileName * @return string|false */ public function getScriptUrl($view, $fileName) { if (($publishedUrl = $this->getPublishedAssetsUrl($view))) { return $publishedUrl . '/' . $this->_scriptDirName . '/' . $fileName; } return false; } /** * Returns the real script Path * * @param string $fileName * @param string $view * @return string|false */ public function getScriptPath($view, $fileName) { if (($path = $this->getAssetsPath($view))) { return $path . DIRECTORY_SEPARATOR . $this->_scriptDirName . DIRECTORY_SEPARATOR . $fileName; } return false; } /** * Returns the published css URL * * @param string $view * @param string $fileName * @return string|false */ public function getCssUrl($view, $fileName) { if (($publishedUrl = $this->getPublishedAssetsUrl($view))) { return $publishedUrl . '/' . $this->_cssDirName . '/' . $fileName; } return false; } /** * Returns the real css path * * @param string $view * @param string $fileName * @return string|false */ public function getCssPath($view, $fileName) { if (($path = $this->getAssetsPath($view))) { return $path . DIRECTORY_SEPARATOR . $this->_cssDirName . DIRECTORY_SEPARATOR . $fileName; } return false; } /** * Returns the published image URL * * @param string $view * @param string $fileName * @return string|false */ public function getImageUrl($view, $fileName) { if (($publishedUrl = $this->getPublishedAssetsUrl($view))) { return $publishedUrl . '/' . $this->_imageDirName . '/' . $fileName; } return false; } /** * Returns the real image path * * @param string $view * @param string $fileName * @return string|false */ public function getImagePath($view, $fileName) { if (($path = $this->getAssetsPath($view))) { return $path . DIRECTORY_SEPARATOR . $this->_imageDirName . DIRECTORY_SEPARATOR . $fileName; } return false; } /** * Returns alias of assets * * @param string $view * @return string|false */ protected function getAssetsPath($view) { if (!array_key_exists($view, $this->_assetsPaths)) { $assetPath = false; $viewPath = $this->getViewFile($view); if ($viewPath) { if (($pos = strrpos($viewPath, DIRECTORY_SEPARATOR . 'views' . DIRECTORY_SEPARATOR)) !== false) { $extension = ($renderer=Yii::app()->getViewRenderer()) !== null ? $renderer->fileExtension : '.php'; $assetPath = substr($viewPath, 0, $pos) . DIRECTORY_SEPARATOR . 'assets' . substr($viewPath, $pos + 1 + strlen('views')); $assetPath = dirname($assetPath) . DIRECTORY_SEPARATOR . basename($assetPath, $extension); } } $this->_assetsPaths[$view] = $assetPath; } return $this->_assetsPaths[$view]; } /** * Returns the published asset URL * * @param string $view * @return string|false */ public function getPublishedAssetsUrl($view) { if (!array_key_exists($view, $this->_assetsUrl)) { $assetsUrl = false; $assetsPath = $this->getAssetsPath($view); if ($assetsPath) { $assetsUrl = Yii::app()->assetManager->publish($assetsPath); } $this->_assetsUrl[$view] = $assetsUrl; } return $this->_assetsUrl[$view]; }
      
      





仕組みを見てみましょう。 「beforeRender($ view)」では、レンダリングの前にメソッドが呼び出されます。



 //   (      assets/{controllerName}/{viewName}/js/index.js) _setupScript($view) //   (      assets/{controllerName}/{viewName}/css/index.css) _setupCss($view)
      
      





特定のビューファイルに対応するcssファイルとjsファイルを自動的に接続します。



さらに、ここで「beforeRender()」では、スタイルとスクリプト(定義されている場合)を接続するための追加のメソッドが起動されます。 これらのメソッドと以前のメソッドの違いは、特定のビューファイルに関連付けられていることです。 つまり ビューファイルの名前は、対応するメソッドの名前の形成に関係します。たとえば、スクリプトのメソッドの名前は、ルール: "_setupScript" + "キャメル表記のビューファイルの名前"、スタイル: "_setupCss" + "キャメル表記のビューファイルの名前"です。



また、次のメソッドを使用できるようになりました。



公開されたリソースへのURLを返すメソッド:

 getScriptUrl($view, $fileName) //  URL   js  getCssUrl($view, $fileName) //  URL   css  getImageUrl($view, $fileName) //  URL    
      
      





リソースの実際のパスを返すメソッド(protectedのassetフォルダー内):

 getScriptPath($view, $fileName) //    js  getCssPath($view, $fileName) //    css  getImagePath($view, $fileName) //     
      
      





そして一般的な方法:

 getAssetsAlias($view) //     "assets",    protected getPublishedAssetsUrl($view) //  URL     "assets"
      
      





ディレクトリー(js、cssファイルおよびイメージの場合)およびファイルの名前は、コントローラークラスのプロパティでデフォルトで定義されます。

 protected $_cssDirName = 'css'; protected $_defaultCssFile = 'index.css'; protected $_scriptDirName = 'js'; protected $_defaultScriptFile = 'index.js'; protected $_imageDirName = 'images';
      
      





したがって、必要なものに変更できます。 オプションで、それらをアプリケーション構成に入れて、コードに簡単な変更を加えることができます。



使用します。


コントローラビューのすべての可能なファイルにcssファイルを含める必要がある場合は、「_ setupCss($ビュー)」メソッドをオーバーライドできます。

 /** * Setup css files * * @param string $view * @return void */ protected function _setupCss($view) { parent::_setupCss($view); //   my_css_file.css     Yii::app()->clientScript->registerCssFile($this->getCssUrl($view, 'my_css_file.css')); }
      
      





または、特定のビューファイルにcssファイルを含める必要がある場合は、メソッド「_setupCss」+「キャメル表記のビューファイルの名前」を定義します。

 /** * Setup css files * * @param string $view * @return void */ protected function _setupCssRegistration($view) { Yii::app()->clientScript->registerCssFile($this->getCssUrl($view, 'my_css_file.css')); }
      
      





このメソッドは、登録をレンダリングするときにのみ呼び出されます



写真は次のようにして取得できます。

 CHtml::image($this->getImageUrl($view));
      
      







それだけです ご清聴ありがとうございました。



All Articles