У меня есть десятки шаблонов, разработанных веб-дизайнером. В основном это HTML, с несколькими тегами PHP и данными. Проблема в том, что мне нужно повторно использовать эти шаблоны (tpl.php) для отправки электронной почты, а тело письма (через PHPMailer) является переменной. Мне удалось заполнить переменную выводом HTML в примере кода (адаптировано). Мой вопрос: я должен переделать все шаблоны или это правильный подход?
<?php
print "This will print just the 'hello world' output. I don't need to print the function as it has no return value<br />";
hola_mundo(); // I directly call the function and it outputs HTML to the screen
print "<br />";
// Now the assignment to the variable.
ob_start(); // I silence the output to screen
hola_mundo();
$string = ob_get_contents(); // I capture the buffer
ob_end_clean(); // I restore the output to screen
print "Now I print the string variable to demonstrate it has captured the HTML ";
print $string;
function hola_mundo(){
?><font color="red"<b>HOLA MUNDO CRUEL</b></font><?php
} // function?>
Более логичным подходом было бы иметь эту функцию (которую я не имею и должен повторить для десятков шаблонов):
<?php
$string = hola_mundo();
print $string;function hola_mundo(){
$string = '<font color="red"<b>HOLA MUNDO CRUEL</b></font>';
return $string
} // function
?>
Вы имеете в виду это?
function getTemplate($file) {
ob_start();
include $file;
return ob_get_clean();
}
// Example usage:
$string = getTemplate('templates/tpl.php');
tpl.php будет выполняться как файл PHP.
Вы даже можете передать переменные в шаблон:
function getTemplate($file, $variables=array()) {
extract($variables);
ob_start();
include $file;
return ob_get_clean();
}
// Example usage:
$string = getTemplate('templates/tpl.php', array('message' => 'Hello world!'));
Это будет извлекать 'Hello world'
в область действия функции, делая ее доступной как $message
переменная к шаблону.
Других решений пока нет …