D
D
dev4002016-05-09 21:37:29
PHP
dev400, 2016-05-09 21:37:29

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

2 answer(s)
P
Philipp, 2016-05-09
@dev400

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!']);

Although in general the idea of ​​using pure PHP as a templating language stinks. I recommend Smarty.

M
Muhammad, 2016-05-09
@muhammad_97

Create a separate template function:

function template($__view, $__data)
{
    extract($__data);

    ob_start();
    
    require $__view;

    $output = ob_get_clean();

    return $output;
}

The arguments are named so as not to occupy the names $view and $data.
In the template (profile.php):
// код
<?php echo $name ?>
// код

Usage:
echo template('views/profile.php', ['username' => 'John']);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question