PHP HTML生成

PHPでhtmlを生成するためのソリューションをご紹介します。 タスクは些細なことのように思えますが、拡張可能で、簡潔であると同時に、優れた機能を備えたいと思います。 それは悪くないようでした。



(多くの人がコメントで考えているように)私はすぐに、タスクはテンプレートエンジンを書くことではなく(非常に多くある)、JavaScriptテンプレートエンジンを置き換えることではないことを言わなければなりません。 本当の方法はhtmlとデータを分離することだということをよく知っています。 しかし、フレームワークのコンポーネントを作成するために、yiiのCGridViewに似たクラスでhtmlを書く必要がありましたが、そのような場所の別のファイルにhtmlを置く価値があります。



主な目標は、クラスと関数でhtmlを取り除くことです。



簡単な例、通常のボタン:



CHtml::create() ->p() ->a(array('href' => 'http://habrahabr.ru', 'class' => 'btn')) ->text('') ->render();
      
      





結果:



 <p><a href="http://habrahabr.ru" class="btn"></a></p>
      
      







トリッキーなことは何もありませんでしたが、これに限定することもできましたが、サイクルが必要でした。

 $arr = array('1' => '', '2' => ''); CHtml::create() ->select($options) ->each(CHtml::plainArray($arr, 'value', 'text')) ->option('array("value" => $data->value)') ->text('$data->text') ->end() ->endEach()
      
      





ここでは、配列をフォームに変換するplainArray()関数を呼び出す必要がありました。

 $arr = array( array('value' => '1', 'text' =>''), array('value' => '2', 'text' => '') );
      
      





ループ内のタグには、eval式を含む関数または文字列、ネスト、テーブルを含む例を含めることができます。



 $columns = array( array('id' => 'NAME', 'label' => ''), array('id' => 'AGE', 'label' => '') ); $data = array( array('NAME' => '', 'AGE' => 29), array('NAME' => '', 'AGE' => 32) ); CHtml::create() ->table() ->thead() ->tr() ->each($columns) ->th() ->text(function($column){ return $column['label']; }) ->end() ->endEach() ->end() ->end() ->tbody() ->each($data) ->tr() ->each($columns) ->td() ->text(function($row, $column) { return $row[$column['id']]; }) ->end() ->endEach() ->end() ->endEach() ->render();
      
      







閉じられていないタグは自動的に閉じられます。



クラスは、フォームで使用するために拡張できます。 各タグの表示方法とその属性について、依存関係を継承または導入することで拡張でき、1つの関数が使用されるため、この動作を簡単にオーバーライドできます。



 class CMyHtml extends CHtml { public function a($options = array()) { $default = array( 'href' => 'javascript:void(0)' ); return parent::a(array_replace($default, $options)); } }
      
      







 class CForm { private $_lastLabel = ''; public function __construct(CModel $model, CHtml $html = null) { $this->_model = $model; $this->_html = $html ?: CHtml::create(); } public function __call($method, $ps) { $options = $ps ? $ps[0]: array(); if ($method === 'label') { $this->_lastLabel = isset($options['for']) ? $this->_model->getLabel($options['for']) : ''; } if ($method === 'text' && $this->_lastLabel) { $options = $options ?: $this->_lastLabel; $this->_lastLabel = ''; } $this->_html->$method($options); return $this; } }
      
      







ソリューション自体はgithubで表示して試すことができます。



ご清聴ありがとうございました。



All Articles