Answer the question
In order to leave comments, you need to log in
Rendering (templating) in pure PHP without special dependencies?
We need an example (piece of code) of a template engine in pure php. What we call in the controller, where we select a template, and pass variables to the view. Solutions from frameworks have dependencies, they are not allowed in this case
Answer the question
In order to leave comments, you need to log in
The correct code should look like this.
/**
* Renders template
*
* @param string 0 Name of your template
* @param mixed 1 Data passed to template
* @return string
*/
function template()
{
extract(func_get_arg(1));
ob_start();
if (file_exists(func_get_arg(0))) {
require func_get_arg(0);
} else {
echo 'Template not found!';
}
return ob_get_clean();
}
// Usage
echo template('30.php', ['hello' => 'world!']);
Create a separate template function:
function template($__view, $__data)
{
extract($__data);
ob_start();
require $__view;
$output = ob_get_clean();
return $output;
}
// код
<?php echo $name ?>
// код
echo template('views/profile.php', ['username' => 'John']);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question