LoginSignup
7
8

More than 5 years have passed since last update.

FuelPHPのHTMLクラスが便利すぎる

Last updated at Posted at 2015-10-28

※フロントエンドの人間が「PHPはそんなにワカンネ」レベルで言っています。

主な使い方

リンクの生成

html::anchor("http://example.com", "example");

結果

<a href="http://example.com">example</a>

画像の生成

html::img("http://example.com/img/photo.jpg", array("alt"=>"image"));

結果

<img src="http://example.com/img/photo.jpg" alt="image">

この辺のももちろん便利なのだが・・・

なんでもアリのhtml_tag関数

リンクの生成

html_tag("a", array("href"=>"http://example.com", "example"));

結果

<a href="http://example.com">example</a>

画像の生成

html_tag("img", array("src"=>"http://example.com/img/photo.jpg", "alt"=>"image"));

結果

<img src="http://example.com/img/photo.jpg" alt="image">

ネストも可能

html_tag("div", array("class"=>"wrap"),
  html_tag("p", array("class"=>"text"), "テキスト").
  html_tag("p", null, "text")
);

結果

<div class="wrap"><p class="text">テキスト</p><p>text</p></div>

便利すぎてFuelPHP以外でも使いたい!
なければ用意すればいい!

html_tag関数を作る

function html_tag($el, $attr, $child = "") {
  $_emptyEl = array("img", "br", "hr", "input", "col", "area", "base", "link", "meta", "param", "source", "track", "wbr", "embed", "command");
  $_attribute = "";
  $_element = "";
  if($attr !== null) {
    foreach($attr as $prop => $value) $_attribute .= ' '.$prop.'="'.$value.'"';
  }

  if(in_array($el, $_emptyEl)) $_element = '<'.$el.$_attribute.'>';
  else $_element = '<'.$el.$_attribute.'>'.$child.'</'.$el.'>';

  return $_element;
}

html_tag関数には3つ引数を渡します。

  • 第1引数:要素名
  • 第2引数:属性配列
  • 第3引数:文字列

要素名

作りたい要素名。HTMLに限らずXMLでも可能。

属性配列

その要素に付加する属性を配列で渡します。
属性を設定しない場合はnullにする。
空属性(disabledrequired)には対応していないので、

html_tag("input", array("type"=>"text", "disabled"=>"disabled"));
<input type="text" disabled="disabled">

このような形になります。(これ自体はinvalidではない)

文字列

作られる要素の子要素がテキストならばそのままそのテキストの文字列を第3引数に渡せばよいです。
入れ子にするならばhtml_tag関数でネストする形にすれば入れ子になります。

7
8
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
8