PHP code example of charcoal / view

1. Go to this page and download the library: Download charcoal/view library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

charcoal / view example snippets


use Charcoal\View\Mustache\MustacheLoader;
use Charcoal\View\Mustache\MustacheEngine;
use Charcoal\View\GenericView;

$loader = new MustacheLoader([
    'base_path' => __DIR__,
    'paths'     => [
        'templates',
        'views',
    ],
]);

$engine = new MustacheEngine([
    'loader' => $loader,
]);

$view = new GenericView([
    'engine' => $engine,
]);

echo $view->render('foo/bar/template', $context);

// A template string can also be used directly, with `renderTemplate()`
$str = 'My name is {{what}}';
echo $view->renderTemplate($str, $context);

use Pimple\Container;
use Charcoal\View\ViewServiceProvider;

$container = new Container([
    'base_path' => __DIR__,
    'view'      => [
        'default_engine' => 'mustache',
        'paths'          => [
            'views',
            'templates',
        ],
    ],
]);
$container->register(new ViewServiceProvider());

echo $container['view']->render('foo/bar/template', $context);

use Charcoal\View\ViewServiceProvider;
use Slim\App;

$app = new App();
$container = $app->getContainer();
$container->register(new ViewServiceProvider());

$app->get('/hello/{name}', function ($request, $response, $args) {
    // This will render the "hello" template
    return $this->renderer->render($response, 'hello', $args);
});

$app->run();

$container->extend('view/mustache/helpers', function(array $helpers, Container $container) {
    return array_merge($helpers, [
        'my_extended_method' => function($text, LambdaHelper $lambda) {
            if (isset($helper)) {
                $text = $helper->render($text);
            }
            return customMethod($text);
        },
    ]);
});

$container['my/twig/helper'] = function (Container $container): MyTwigHelper {
    return new MyTwigHelper();
};

$container->extend('view/twig/helpers', function (array $helpers, Container $container): array {
    return array_merge(
        $helpers,
        $container['my/twig/helper']->toArray(),
    );
});

use \Charcoal\View\ViewableInterface;
use \Charcoal\View\ViewableTrait;

class MyObject implements ViewableInterface
{
    use ViewableTrait;

    public function world()
    {
        return 'world!';
    }
}

$obj = new MyObject();
$obj->renderTemplate('Hello {{world}}');