Menambahkan Direktif Include Pada Parser Codeigniter4
By Harjito
Menambahkan Direktif Include Pada Parser Codeigniter4
Pada tulisan saya terdahulu, saya menuliskan teknik override parser di CodeIgniter 4 agar melewatkan variabel pada plugin. Artikel dapat di baca di sini. Di tutorial kali ini kita akan meningkatkan fitur parser di CodeIgniter 4 dengan direktif include. Diretif include akan memudahkan dalam layouting karena kita dapat menginjeksikan file lain dalam view, seperti kebanyakan template engine.
Tidak perlu berpanjang lebar, code skrip dapat kita lihat di sini
<?php
/* app/Libraries/MyParser.php */
namespace App\Libraries;
use CodeIgniter\View\Parser;
use CodeIgniter\View\Exceptions\ViewException;
use Config\View as ViewConfig;
use ParseError;
use Psr\Log\LoggerInterface;
/**
* Layout
*/
class MyParser extends \CodeIgniter\View\Parser
{
public function __construct()
{
$viewConfig = new \Config\View();
$viewPath = APPPATH . 'Views/';
$loader = \Config\Services::loader();
$debug = CI_DEBUG;
$logger = \Config\Services::logger();
parent::__construct($viewConfig, $viewPath, $loader , $debug, $logger);
}
/**
* Parse a template
*
* Parses pseudo-variables contained in the specified template,
* replacing them with the data in the second param
*
* @param array $options Future options
*/
protected function parse(string $template, array $data = [], ?array $options = null): string
{
if ($template === '') {
return '';
}
$template = $this->includeFile($template);
// Remove any possible PHP tags since we don't support it
// and parseConditionals needs it clean anyway...
$template = str_replace(['<?', '?>'], ['<?', '?>'], $template);
$template = str_replace(['(', ')'], ['#40', '#41'], $template);
// temporarily replace the plugin tag so it doesn't trigger an error during the loop
$template = str_replace(['{+', '+}'], ['#$', '$#'], $template);
$template = $this->parseComments($template);
$template = $this->extractNoparse($template);
// Replace any conditional code here so we don't have to parse as much
$template = $this->parseConditionals($template);
// loop over the data variables, replacing
// the content as we go.
foreach ($data as $key => $val) {
$escape = true;
if (is_array($val)) {
$escape = false;
$replace = $this->parsePair($key, $val, $template);
} else {
$replace = $this->parseSingle($key, (string) $val);
}
foreach ($replace as $pattern => $content) {
$template = $this->replaceSingle($pattern, $content, $template, $escape);
}
}
// return plugin tag before running parsePlugins
$template = str_replace(['#$', '$#'], ['{+', '+}'], $template);
// Handle any plugins before normal data, so that
// it can potentially modify any template between its tags.
$template = $this->parsePlugins($template);
$template = $this->insertNoparse($template);
$template = str_replace(['#40', '#41'], ['(', ')'], $template);
return $template;
}
private function includeFile(string $template){
preg_match_all("/\@include\s+[\"|\'](.+?)[\"|\']/", $template, $matchs);
if(!$matchs) return $template;
$tags = [];
$replacements = [];
foreach($matchs[1] as $index => $match){
$includeFile = $this->viewPath . str_replace('.', '/', $match) . '.php';
if(!file_exists($includeFile)){
throw ViewException::forInvalidFile($includeFile);
}
$replacements[] = file_get_contents($includeFile);
$tags[] = $matchs[0][$index];
}
return str_replace($tags, $replacements, $template);
}
}
Contoh Penggunaan
app/Controllers/Home.php
<?php
namespace App\Controllers;
use App\Libraries\MyParser;
class Home extends BaseController
{
public function index()
{
$parser = new MyParser();
return $parser->setData([
'title'=>'Test Parser Dengan Direktif',
'data'=>[
['line'=>'Line 1],
['line'=>'Line 2],
['line'=>'Line 3],
]])
->render('foo');
}
}
app/Views/foo.php
@include 'partials.header'
{data}
<p>{line}</p>
{/data}
@include 'partials.footer'
app/Views/partials/header.php
<h1>{ title }</h1>
app/Views/partials/footer.php
<p>developed by Harjito</p>
Tampilan Hasil
Test Parser Dengan Direktif
Line 1
Line 2
Line 3
developed by Harjito
Tags:
Ikuti terus tutorial saya di e-Project dan channel
saya di