$smarty->assign('name',$value);
$smarty->display("index.html");
$variables
index.html で自動的に置き換えられるようにしecho
ます。
$smarty->assign('name',$value);
$smarty->display("index.html");
$variables
index.html で自動的に置き換えられるようにしecho
ます。
次のようなものを使用できます。
// assigns the output of a file into a variable...
function get_include_contents($filename, $data='') {
if (is_file($filename)) {
if (is_array($data)) {
extract($data);
}
ob_start();
include $filename;
$contents = ob_get_contents();
ob_end_clean();
return $contents;
}
return false;
}
$data = array('name'=>'Ross', 'hobby'=>'Writing Random Code');
$output = get_include_contents('my_file.php', $data);
// my_file.php will now have access to the variables $name and $hobby
前の質問から引用
class Templater {
protected $_data= array();
function assign($name,$value) {
$this->_data[$name]= $value;
}
function render($template_file) {
extract($this->_data);
include($template_file);
}
}
$template= new Templater();
$template->assign('myvariable', 'My Value');
$template->render('path/to/file.tpl');
テンプレートで
<?= $foobar ?>
foobar .... を出力します。独自の構文を作成する必要がある場合は、使用できますpreg_replace_callback
例えば :
function replace_var($matches){
global $data;
return $data[$matches[1]];
}
preg_replace_callback('/{$([\w_0-9\-]+)}/', 'replace_var');
前の回答の Templater クラスを使用すると、render 関数を変更して正規表現を使用できます
function render($template_file) {
$patterns= array();
$values= array();
foreach ($this->_data as $name=>$value) {
$patterns[]= "/\\\$$name/";
$values[]= $value;
}
$template= file_get_contents($template_file);
echo preg_replace($patterns, $values, $template);
}
......
$templater= new Templater();
$templater->assign('myvariable', 'My Value');
$templater->render('mytemplate.tpl');
そして、次のテンプレート ファイル:
<html>
<body>
This is my variable <b>$myvariable</b>
</body>
</html>
レンダリングします:
これは私の変数ですMy Value
免責事項: 実際にこれを実行して動作するかどうかを確認していません! preg_replace の PHP マニュアル、例 #2 を参照してください: http://php.net/manual/en/function.preg-replace.php
説明する機能は、 extract php 関数によって処理されます。次に例を示します。
// Source: http://www.php.net/manual/en/function.extract.php
$size = "large";
$var_array = array("color" => "blue", "size" => "medium", "shape" => "sphere");
extract($var_array, EXTR_PREFIX_SAME, "wddx");
echo "$color, $size, $shape, $wddx_size\n";
しかし、Sergey または RageZ によって投稿されたクラスの 1 つを使用することを強くお勧めします。それ以外の場合は車輪を再発明することになるため、実際には多くの人が PHP で利用できるロープロファイルおよびハイエンドのテンプレート クラスがたくさんあります :)