I 开发者_运维问答am trying to build my own simple template handler to easily be able to nest and combine files into variables and call these variables when neccessary, as shown below:
$partial['header'] = 'header.php';
foreach($partial as $part => $view ) {
$output[$name] = file_get_contents( APPPATH .'views/' . $view . '.php' );
}
extract($output, EXTR_PREFIX_ALL, 'template' );
include 'mytemplate.php';
The mytemplate.php
template file:
<?php
echo $template_header; // Shows the header.
The question:
Obviously, loading a PHP file byfile_get_contents
isn't going to call any PHP code inside the loaded file and I am sure that there's better options available then using eval
. What should I change to be able to use PHP inside my template files? More ugly is possible but doing exactly what you're wanting :
function custom_get_content($filename){
if (is_file($filename)) {
ob_start();
include $filename;
$contents = ob_get_contents();
ob_end_clean();
return $contents;
}
}
Then you can call it :
foreach($partial as $part => $view ) {
$output[$name] = custom_get_content( APPPATH .'views/' . $view . '.php' );
}
I copied that from a comment in the PHP manual but can't find it anymore (and that's why maybe it's too ugly :D)
Reading the scripts in is obiously not the best approach. You'll have to eval
them.
And just for the record:
include($filename);
Is functionally identical to:
eval("?>" . file_get_contents($filename));
Get over it. The "eval is evil" meme is just that, a meme. So if you want to keep your appraoch, you could just use eval("?>$template_header");
instead of echo
.
The alternative would be to skip the file reading, and have your $template_vars
contain filenames rather than their content. Then do an ordinary include($template_header);
精彩评论