Created
February 14, 2015 02:47
-
-
Save kwatch/0d7791fa879736669c3a to your computer and use it in GitHub Desktop.
HTMLテンプレートにどんな変数を渡したかをわかりやすくするための工夫 in PHP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ### | |
| ### templating.php | |
| ### | |
| <?php | |
| function h($str) { | |
| return htmlspecialchars($str, ENT_QUOTES, 'UTF-8'); | |
| } | |
| function print_template($template_filename, $vars) { ## テンプレートへの値は連想配列$varsで渡す | |
| include($template_filename); | |
| } | |
| function render_template($template_filename, $vars) { ## テンプレートへの値は連想配列$varsで渡す | |
| ob_start(); | |
| include($template_filename); | |
| return ob_get_clean(); | |
| } | |
| ### | |
| ### index.html.php | |
| ### テンプレートへ渡された値は$varsで参照するので、どの値が渡されたか分かりやすい。 | |
| ### または面倒でなければ、冒頭で $items = $vars['items']; ... のようにしてもよい。 | |
| ### | |
| <!doctype html> | |
| <body> | |
| <h1><?= h($vars['page_title']) ?></h1> | |
| <ul> | |
| <?php foreach ($vars['items'] as $item): ?> | |
| <li><?= h($item) ?></li> | |
| <?php endforeach ?> | |
| </ul> | |
| </body> | |
| ### | |
| ### example.php | |
| ### | |
| <?php | |
| include_once('templating.php'); | |
| ## 連想配列をテンプレートへ渡す | |
| $vars = [ | |
| 'page_title' => "Sample Page", | |
| 'items' => ["string", 123, true, null], | |
| ]; | |
| print_template('index.html.php', $vars); | |
| //echo render_template('index.html.php', $vars); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment