PHPackages                             locomotivemtl/charcoal-view - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Templating &amp; Views](/categories/templating)
4. /
5. locomotivemtl/charcoal-view

ActiveLibrary[Templating &amp; Views](/categories/templating)

locomotivemtl/charcoal-view
===========================

Charcoal View (templates rendering and tools)

0.4.0(6y ago)123.8k4MITPHPPHP &gt;=5.6.0 || &gt;=7.0

Since Feb 4Pushed 5y ago12 watchersCompare

[ Source](https://github.com/locomotivemtl/charcoal-view)[ Packagist](https://packagist.org/packages/locomotivemtl/charcoal-view)[ Docs](https://charcoal.locomotive.ca)[ RSS](/packages/locomotivemtl-charcoal-view/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (12)Versions (21)Used By (4)

Charcoal View
=============

[](#charcoal-view)

The `Charcoal\View` module (`locomotivemtl/charcoal-view`) provides everything needed to render templates and add renderer to objects.

It is a thin layer on top of various *rendering engines*, such as **mustache** or **twig** that can be used either as a *View* component with any frameworks, as PSR-7 renderer for such frameworks (such as Slim)

It is the default view layer for `charcoal-app` projects.

[![Build Status](https://camo.githubusercontent.com/ca225733998bc9c63d544f7e849f3c921307e400032d64f33ce9d3d0bc8062ca/68747470733a2f2f7472617669732d63692e6f72672f6c6f636f6d6f746976656d746c2f63686172636f616c2d766965772e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/locomotivemtl/charcoal-view)[![SensioLabsInsight](https://camo.githubusercontent.com/b5acbc0d86ae3d3fb674eca831b2c29ab7cb1c2a8cf92f67e43a1bec064c7504/68747470733a2f2f696e73696768742e73656e73696f6c6162732e636f6d2f70726f6a656374732f33393664326630362d383262612d346337392d623863632d3736326631653862646132392f6d696e692e706e67)](https://insight.sensiolabs.com/projects/396d2f06-82ba-4c79-b8cc-762f1e8bda29)

Table of content
================

[](#table-of-content)

- [How to install](#how-to-install)
    - [Dependencies](#dependencies)
- [Basic Usage](#basic-usage)
    - [Using the Renderer, with Slim](#using-the-renderer-with-slim)
- [Module components](#module-components)
    - [Views](#views)
        - [Generic View](#generic-view)
    - [View Engines](#view-engines)
        - [Mustache Helpers](#mustache-helpers)
    - [Loaders](#loaders)
        - [Templates](#templates)
    - [Viewable Interface and Trait](#viewable-interface-and-trait)
    - [View Service Provider](#view-service-provider)
- [Development](#development)
    - [Development dependencies](#development-dependencies)
    - [Coding Style](#coding-style)
    - [Authors](#authors)

How to install
==============

[](#how-to-install)

The preferred (and only supported) way of installing charcoal-view is with **composer**:

```
$ composer require locomotivemtl/charcoal-view
```

To install a full Charcoal project, which includes `charcoal-view`:

```
$ composer create-project locomotivemtl/charcoal-project-boilerplate:@dev --prefer-source
```

Dependencies
------------

[](#dependencies)

- `PHP 7.1+`
    - Older versions of PHP are deprecated, therefore not supported.
- [`psr/http-message`](http://www.php-fig.org/psr/psr-7/)
    - Charcoal View provides a PSR7 renderer.
- [`locomotivemtl/charcoal-config`](https://github.com/locomotivemtl/charcoal-config)
    - The view objects are *configurable* with `\Charcoal\View\ViewConfig`. [`locomotivemtl/charcoal-translator`](https://github.com/locomotivemtl/charcoal-translator)
    - The translator service
- [`erusev/parsedown`](https://github.com/erusev/parsedown)
    - A markdown parser, which is provided to engines or could be used as a service.

### Optional dependencies

[](#optional-dependencies)

- [`mustache/mustache`](https://github.com/bobthecow/mustache.php)
    - The default rendering engine is *mustache*, so it should be included in most cases.
    - All default charcoal modules use mustache templates.
- [`twig/twig`](http://twig.sensiolabs.org/)
    - Twig can also be used as a rendering engine for the view.
- [`pimple/pimple`](http://pimple.sensiolabs.org/)
    - Dependencies management can be done with a Pimple ServiceProvider(`\Charcoal\View\ViewServiceProvider`)
    - It is actually required by default in `charcoal-app`.

> 👉 Development dependencies are described in the *Development* section of this README file.

Basic Usage
===========

[](#basic-usage)

A `View` can be used to render any template (which can be loaded from the engine) with any object (or array, for twig) as context.

```
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);
```

Basic Usage, with service provider
----------------------------------

[](#basic-usage-with-service-provider)

All this bootstrapping code can be avoided by using the `ViewServiceProvider`. This provider expects a `config` object

```
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);
```

> 👉 The default view engine, used in those examples, would be *mustache*.

Using the Renderer, with Slim
-----------------------------

[](#using-the-renderer-with-slim)

A view can also be implicitely used as a rendering service. Using the provided `view/renderer`, with a PSR7 framework (in this example, Slim 3):

```
use Charcoal\View\ViewServiceProvider;

include 'vendor/autoload.php';

$app = new \Slim\App();
$container = $app->getContainer();
$container->register(new ServiceProvider());

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

$app->run();
```

> Just like the view, it is possible to simply register all dependencies on a Pimple container (with the `ViewServiceProvider`) to avoid all this bootstrapping code. The renderer is available as `$container['view/renderer']`.

Module components
=================

[](#module-components)

The basic components in `charcoal-view` are:

- [**View**](#views), which provide the basic interface to all components.
- [**Engine**](#view-engines), to actually render the templates.
- [**Loader**](#loader), to load *template files*.
- [**Viewable**](#viewable-interface-and-trait), which allow any object to be rendered with a *View*.
- **Renderer**, an extra helper to use a view to render into PSR-7 request/response objects.

Views
-----

[](#views)

The `Charcoal\View\ViewInterface` defines all that is needed to render templates via a view engine:

- `render($templateIdent = null, $context = null)`
- `renderTemplate($templateString, $context = null)`

The abstract class `Charcoal\View\AbstractView` fully implements the `ViewInterface` and adds the methods:

### Generic view

[](#generic-view)

As convenience, the `\Charcoal\View\GenericView` class implements the full interface by extending the `AbstractView` base class.

View Engines
------------

[](#view-engines)

Charcoal *views* support different templating Engines\_, which are responsible for loading the appropriate template (through a *loader*) and render a template with a given context according to its internal rules. Every view engines should implement `\Charcoal\View\EngineInterface`.

There are 3 engines available by default:

- `mustache` (**default**)
- `php`
- `twig`

### Mustache Helpers

[](#mustache-helpers)

Mustache can be extended with the help of `helpers`. Those helpers can be set by extending `view/mustache/helpers` in the container:

```
$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);
        }
    ]);
});

```

*Provided helpers:*

- **Assets** helpers:
    - `purgeJs`
    - `addJs`
    - `js`
    - `addJsRequirement`
    - `jsRequirements`
    - `addCss`
    - `purgeCss`
    - `css`
    - `addCssRequirement`
    - `cssRequirements`
    - `purgeAssets`
- **Translator** helpers:
    - `_t` Translate a string with `{{#_t}}String to translate{{/_t}}`
- **Markdown** helpers:
    - `markdown` Parse markdown to HTML with `{{#markdown}}# this is a H1{{/markdown}}`

Loaders
-------

[](#loaders)

A `Loader` service is attached to every engine. Its function is to load a given template content

### Templates

[](#templates)

Templates are simply files, stored on the filesystem, containing the main view (typically, HTML code + templating tags, but can be kind of text data).

- For the *mustache* engine, they are `.mustache` files.
- For the *php* engine, they are `.php` files.

Templates are loaded with template *loaders*. Loaders implement the `Charcoal\View\LoaderInterface` and simply tries to match an identifier (passed as argument to the `load()` method) to a file on the filesystem.

Calling `$view->render($templateIdent, $context)` will automatically use the engine's `Loader` object to find the template `$templateIdent`.

Otherwise, calling `$view->renderTemplate($templateString, $context)` expects an already-loaded template string as parameter.

Viewable Interface and Trait
----------------------------

[](#viewable-interface-and-trait)

Any objects can be made renderable (viewable) by implementing the `Charcoal\View\ViewableInterface` by using the `Charcoal\View\ViewableTrait`.

The interface adds the following methods to their implementing objects:

- `setTemplateIdent($ident)`
- `templateIdent()`
- `setView($view)`
- `view()`
- `render($templateIdent = null)`
- `renderTemplate($templateString)`

### Examples

[](#examples)

Given the following classes:

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

class MyObject implements ViewableInterface
{
    use ViewableTrait;

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

The following code:

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

would output: `"Hello world!"`

View Service Provider
---------------------

[](#view-service-provider)

As seen in the various examples above, it is recommended to use the `ViewServiceProvider` to set up the various dependencies, according to a `config`, on a `Pimple` container.

The Service Provider adds the following service to a container:

- `view` The base view instance.
- `view/renderer` A PSR-7 view renderer.
- `view/parsedown` A parsedown service, to render markdown into HTML.

Other services / options are:

- `view/config` View configuration options.
- `view/engine` Currently used view engine.
- `view/loader` Currently used template loader.

The `ViewServiceProvider` expects the following services / keys to be set on the container:

- `config` Application configuration. Should contain a "view" key to build the *ViewConfig* obejct.

### The View Config

[](#the-view-config)

Most service options can be set dynamically from a configuration object (available in `$container['view/config']`).

Example:

```
{
    "base_path":"/",
    "view": {
        "engine":"mustache",
        "paths":[
            "templates",
            "views"
        ]
    }
}
```

Development
===========

[](#development)

To install the development environment:

```
$ composer install --prefer-source
```

Run tests with

```
$ composer test
```

API documentation
-----------------

[](#api-documentation)

- The auto-generated `phpDocumentor` API documentation is available at
- The auto-generated `apigen` API documentation is available at [https://codedoc.pub/locomotivemtl/charcoal-view/master/](https://codedoc.pub/locomotivemtl/charcoal-view/master/index.html)

Development dependencies
------------------------

[](#development-dependencies)

- `phpunit/phpunit`
- `squizlabs/php_codesniffer`
- `satooshi/php-coveralls`
- `pimple/pimple`
- `mustache/mustache`
- `twig/twig`

Continuous Integration
----------------------

[](#continuous-integration)

ServiceBadgeDescription[Travis](https://travis-ci.org/locomotivemtl/charcoal-view)[![Build Status](https://camo.githubusercontent.com/ca225733998bc9c63d544f7e849f3c921307e400032d64f33ce9d3d0bc8062ca/68747470733a2f2f7472617669732d63692e6f72672f6c6f636f6d6f746976656d746c2f63686172636f616c2d766965772e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/locomotivemtl/charcoal-view)Runs code sniff check and unit tests. Auto-generates API documentation.[Scrutinizer](https://scrutinizer-ci.com/g/locomotivemtl/charcoal-view/)[![Scrutinizer Code Quality](https://camo.githubusercontent.com/5511c32cd8b3d9f2db32ab7a04cef45cf63807220d354686fc5ddb3ccbfc97e1/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f6c6f636f6d6f746976656d746c2f63686172636f616c2d766965772f6261646765732f7175616c6974792d73636f72652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/locomotivemtl/charcoal-view/?branch=master)Code quality checker. Also validates API documentation quality.[Coveralls](https://coveralls.io/github/locomotivemtl/charcoal-view)[![Coverage Status](https://camo.githubusercontent.com/4d50308d22c86ca7884d3a33c86f585a3f8a29fc873cc8604a85c272885884ea/68747470733a2f2f636f766572616c6c732e696f2f7265706f732f6769746875622f6c6f636f6d6f746976656d746c2f63686172636f616c2d766965772f62616467652e7376673f6272616e63683d6d6173746572)](https://coveralls.io/github/locomotivemtl/charcoal-view?branch=master)Unit Tests code coverage.[Sensiolabs](https://insight.sensiolabs.com/projects/396d2f06-82ba-4c79-b8cc-762f1e8bda29)[![SensioLabsInsight](https://camo.githubusercontent.com/b5acbc0d86ae3d3fb674eca831b2c29ab7cb1c2a8cf92f67e43a1bec064c7504/68747470733a2f2f696e73696768742e73656e73696f6c6162732e636f6d2f70726f6a656374732f33393664326630362d383262612d346337392d623863632d3736326631653862646132392f6d696e692e706e67)](https://insight.sensiolabs.com/projects/396d2f06-82ba-4c79-b8cc-762f1e8bda29)Another code quality checker, focused on PHP.Coding Style
------------

[](#coding-style)

The Charcoal-View module follows the Charcoal coding-style:

- [*PSR-1*](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-1-basic-coding-standard.md)
- [*PSR-2*](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)
- [*PSR-4*](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-4-autoloader.md), autoloading is therefore provided by *Composer*.
- [*phpDocumentor*](http://phpdoc.org/) comments.
- Read the [phpcs.xml](phpcs.xml) file for all the details on code style.

> Coding style validation / enforcement can be performed with `composer phpcs`. An auto-fixer is also available with `composer phpcbf`.

Authors
=======

[](#authors)

- Mathieu Ducharme
- [Locomotive](https://locomotive.ca)

License
=======

[](#license)

Charcoal is licensed under the MIT license. See [LICENSE](LICENSE) for details.

###  Health Score

32

—

LowBetter than 72% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity24

Limited adoption so far

Community20

Small or concentrated contributor base

Maturity57

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 74.3% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~85 days

Recently: every ~174 days

Total

17

Last Release

2381d ago

PHP version history (3 changes)0.1PHP &gt;=5.5.0

0.1.5PHP &gt;=5.6.0

0.3.4PHP &gt;=5.6.0 || &gt;=7.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/cfb071c0ff7ce9500c528a003a2c53124248debc3e5bf367c17f89f5e6136125?d=identicon)[mducharme](/maintainers/mducharme)

---

Top Contributors

[![mducharme](https://avatars.githubusercontent.com/u/12157?v=4)](https://github.com/mducharme "mducharme (162 commits)")[![mcaskill](https://avatars.githubusercontent.com/u/29353?v=4)](https://github.com/mcaskill "mcaskill (50 commits)")[![BeneRoch](https://avatars.githubusercontent.com/u/3017380?v=4)](https://github.com/BeneRoch "BeneRoch (3 commits)")[![JoelAlphonso](https://avatars.githubusercontent.com/u/10762266?v=4)](https://github.com/JoelAlphonso "JoelAlphonso (3 commits)")

---

Tags

twigmustacheviewtemplatescharcoal

###  Code Quality

TestsPHPUnit

Code StylePHP\_CodeSniffer

### Embed Badge

![Health badge](/badges/locomotivemtl-charcoal-view/health.svg)

```
[![Health](https://phpackages.com/badges/locomotivemtl-charcoal-view/health.svg)](https://phpackages.com/packages/locomotivemtl-charcoal-view)
```

###  Alternatives

[shoot/shoot

Shoot aims to make providing data to your templates more manageable

40229.9k2](/packages/shoot-shoot)[laminas/laminas-view

Fast and type safe HTML templating library with a flexible plugin system supporting multistep template composition

7526.3M230](/packages/laminas-laminas-view)[wyrihaximus/twig-view

Twig powered View for CakePHP

804.7M1](/packages/wyrihaximus-twig-view)[san-kumar/laravel-crud

Laravel CRUD generator: Generate CRUD for any db table with the crud:generate command.

564.4k](/packages/san-kumar-laravel-crud)[daycry/twig

twig for Codeigniter 4

145.1k2](/packages/daycry-twig)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
