テンプレートエンジンの考察
- javascriptのようにテンプレートを変数に格納して使う。 -> jquery-tmpl-php
- htmltemplate for PHP (鮎川寛氏作) -> htmltemplate for PHP(includeを調整していないので動かん)
- -> 上記使い方解説
- -> php マイクロテンプレート
- -> php テンプレートエンジン自作してみた!
//CODE
//冒頭で関数ファイルを読み込む
$dirname = dirname(__FILE__);
include($dirname . '/php_test_funcclass.php');
//関数クラス
class ninjaTemplate {
public function show($tpl_file) {
include("{$tpl_file}");
}
}
//JSONファイルをテンプレに当てはめる
//これがJSON
{"contents":[{
"label":"ホームページアドレス(UR)",
"name":"hplink",
"type":"input",
"content":"https://www.denso.com/jp/ja/",
"class":"w-100",
"hint":""
},{
"label":"リンク画像(ない場合は自動生成されます。)",
"name":"linkimage",
"type":"image",
"content":"",
"class":"w-100",
"hint":""
},{
"label":"紹介文",
"name":"guide",
"type":"cktext",
"content":"株式会社デンソーは\n",
"class":"w-100",
"hint":""
}],
"group":"","tabs":""
}
//jsonをエンコード、さらにデコード
$json = file_get_contents($dirname . '/test_json.json');
$json = mb_convert_encoding($json, 'UTF8', 'ASCII,JIS,UTF-8,EUC-JP,SJIS-WIN');
$jsonData = json_decode($json, true);
//配列変換したJSONをテンプレート関数に当てはめる
$ninjaTemplate = new ninjaTemplate();
$ninjaTemplate->jsonData = $jsonData;
$ninjaTemplate->show($dirname . '/php_test_tmpl.php');
//テンプレート内では、配列から変数生成して、当てはめる
for($i=0; $ijsonData['contents']); $i++){
$name = $this->jsonData['contents'][$i]['name'];
$label = $this->jsonData['contents'][$i]['label'];
$content = $this->jsonData['contents'][$i]['content'];
if($name == 'hplink') $hplink = $this->jsonData['contents'][$i]['content'];
if($name == 'guide') $guide = $this->jsonData['contents'][$i]['content'];
if($name == 'linkimage') $img = $this->jsonData['contents'][$i]['content'];
}
↓↓↓↓↓ これが出力 ↓↓↓↓↓