php: simple template renderer implementation

Trabla: php: simple template renderer implementation

Solving: 

<?php

/**
* Super simple template renderer :)
* Loads file from $path input param
* Replace {$var} in loaded file if found key in $params assoc array
**/


class Renderer{

public static function render( $path , $params ){

$html = ''; 

if( file_exists($path)){

$html = file_get_contents($path);

if( is_array($params)){

foreach ($params as $key => $value) {

$key = '{$'.$key.'}';

$html = str_replace( $key, $value , $html );

}

}

}

return $html;

}

}
?>

Example:

Create simple project ( using xampp ) :

1. Simple Router.php  from post:
http://codingtrabla.blogspot.com/2014/11/php-simple-router-implementation.html

C:\xampp\htdocs\test\Router.php

2. Renderer.php file and copy code above

C:\xampp\htdocs\test\Renderer.php

3. File view.html with following code

C:\xampp\htdocs\test\view.html

<html>
<body>
Hello <b>{$user}</b> </br>
Your motto: <b>{$motto}</b>
</body>
</html>

4.  index.php file with following code:

<?php

require_once 'C:\xampp\htdocs\test\Router.php' ;
require_once 'C:\xampp\htdocs\test\Renderer.php' ;

$app = new Router();

//Home
$app->setDefault( function(){
    
     echo Renderer::render(  'C:\xampp\htdocs\test\view.html' , array( 
              'user' => 'Gandalf' ,
              'motto' => 'You shall not pass!!!'
      ) );

});

$app->run();

?>

Result:


php: simple template renderer implementation


No comments:

Post a Comment