Skip to content

Instantly share code, notes, and snippets.

@maruware
Created July 14, 2015 12:27
Show Gist options
  • Save maruware/ce5fb3a6fd8426d2f829 to your computer and use it in GitHub Desktop.
Save maruware/ce5fb3a6fd8426d2f829 to your computer and use it in GitHub Desktop.
Evaluate Template
<?php
$hoge = 123;
?>
<Sample>
<hoge><?=$hoge?></hoge>
<fuga><?=$fuga?></fuga>
</Sample>
<?php
class TemplateUtil{
public static function evalTemplate($template_file, $vars)
{
ob_start();
foreach($vars as $key=>$val){
${$key} = $val;
}
require($template_file);
$contents = ob_get_contents();
ob_end_clean();
return $contents;
}
}
<?php
require_once('TemplateUtil.php');
class TemplateUtilTest extends PHPUnit_Framework_TestCase{
public function test_evalTemplate()
{
$template_file = 'sample.xml.tmpl';
$contents = TemplateUtil::evalTemplate($template_file, ['fuga'=>'456']);
$expect = <<<XML
<Sample>
<hoge>123</hoge>
<fuga>456</fuga>
</Sample>
XML;
$this->assertEquals($expect, $contents);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment