PHPackages                             djmattyg007/handlebars - 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. djmattyg007/handlebars

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

djmattyg007/handlebars
======================

PHP implementation of Handlebars templates aiming to match the JS interface.

7.1.0(8y ago)312.0k—0%MITPHPPHP &gt;=7.0.8

Since Jun 27Pushed 8y ago2 watchersCompare

[ Source](https://github.com/djmattyg007/Handlebars)[ Packagist](https://packagist.org/packages/djmattyg007/handlebars)[ Docs](https://github.com/djmattyg007/handlebars)[ RSS](/packages/djmattyg007-handlebars/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (3)Dependencies (2)Versions (6)Used By (0)

Handlebars for PHP
==================

[](#handlebars-for-php)

Install
-------

[](#install)

`composer require djmattyg007/handlebars`

Introduction
------------

[](#introduction)

This is a PHP implementation of Handlebars templates that aims to match the interface of the JS implementation. It does not provide some of the niceties found in other similar PHP libraries, such as loading templates from files.

This is a fork of the Handlebars package from the Eden framework. It has been refactored to not rely on the magic provided by the Core package from Eden, and to not treat most of the classes as singletons. It also takes advantage of scalar type declarations available in PHP 7.

Basic Usage
-----------

[](#basic-usage)

#### Instantiating the Handlebars class

[](#instantiating-the-handlebars-class)

There are several parts to the Handlebars object. The first is the Runtime object. The Runtime is what ends up containing all helpers and partials. It is passed to Templates when they are compiled, and also the Compiler for use during compilation.

```
use MattyG\Handlebars\Runtime;
$runtime = new Runtime();
// Pass false to the constructor to have it not load the default Helpers
$helperlessRuntime = new Runtime(false);
```

Next, we need a factory to generate Argument Parsers. This itself requires a factory to generate Argument Lists.

```
use MattyG\Handlebars\Argument\ArgumentListFactory;
use MattyG\Handlebars\Argument\ArgumentParserFactory;
$argumentParserFactory = new ArgumentParserFactory(new ArgumentListFactory());
```

The Compiler has three dependencies: the Runtime, a factory to produce Tokenizers, and a factory to produce Argument Parsers. Each time a new Template is compiled, a new Tokenizer is created using the Tokernizer factory. While a template is being compiled, a new Argument Parser is created using the Argumetn Parser factory whenever a non-partial tag is found in the template.

```
use MattyG\Handlebars\Compiler;
use MattyG\Handlebars\TokenizerFactory;
$compiler = new Compiler($runtime, new TokenizerFactory(), $argumentParserFactory);
```

Finally, we instanstiate the actual Handlebars object. This is the object you'll be interacting with to register helpers and partials, and to compile templates. It has three dependencies: the Runtime, the Compiler, and a factory to produce Data objects. Data objects are used to help easily navigate the context provided when rendering a Template.

```
use MattyG\Handlebars\DataFactory;
use MattyG\Handlebars\Handlebars;
$handlebars = new Handlebars($runtime, $compiler, new DataFactory());
```

It is recommended that you use a dependency injection system to handle construction of the main Handlebars object, so that the only part you need to worry about is registering your helpers and partials, and actually compiling your templates.

Alternatively, you can use a new convenience function for when you don't care about swapping out any of the components:

```
use MattyG\Handlebars\Handlebars;
$handlebars = Handlebars::newInstance();
```

The `newInstance()` method accepts the same boolean parameter as the `Runtime` constructor, so you can still easily prevent the automatic addition of the default helpers.

#### Rendering

[](#rendering)

```
$template = $handlebars->compile('{{foo}} {{bar}}');

$content = $template->render(array('foo' => BAR, 'bar' =. 'ZOO'));
// Or used as a callable
$content = $template(array('foo' => 'BAZ', 'bar' => 'ABC'));
```

#### Registering Helpers

[](#registering-helpers)

```
$handlebars->registerHelper('bar', function($options) {
    return 'BAZ';
});
$template = $handlebars->compile('{{foo}} {{bar}}');
echo $template(array('foo' => 'BAR'));
```

#### Registering Partials

[](#registering-partials)

```
$handlebars->registerPartial('bar' => 'ABC');
$template = $handlebars->compile('{{foo}} {{> bar}}');
echo $template->render(array('foo' => 'BAR'));
```

Features
--------

[](#features)

- PHP API - designed to match the handlebars.js documentation
    - registerHelper() - matches exactly what you expect from handlebars.js (except it's PHP syntax)
    - registerPartial() - accepts strings and functions as callbacks
    - Literals like `{{./foo}}` and `{{../bar}}` are evaluated properly
    - Comments like `{{!-- Something --}}` and `{{! Something }}` supported
    - Trims like `{{~#each}}` and `{{~foo~}}` supported
    - Mustache backwards compatibility `{{#foo}}{{this}}{{/foo}}`
    - SafeString class, to allow helpers to return HTML
- Default Helpers matching handlebars.js
    - if
    - each - and `{{#each foo as |value, key|}}`
    - unless
    - with

Production Ready
----------------

[](#production-ready)

When your templates are ready for a production (live) environment, it is recommended that caching be used. To enable cache:

- Create a cache folder and make sure permissions are properly set for handlebars to write files to it.
- Enable cache by using `$handlebars->setCachePath(__DIR__ . '/your/cache/folder/location');`
- The code will not attempt to create the specified folder if it doesn't exist.

API
---

[](#api)

### compile

[](#compile)

Returns a template object containing the compiled code for the supplied template string.

#### Usage

[](#usage)

```
$template = $handlebars->compile(string $string);
```

#### Parameters

[](#parameters)

- `string $string` - the template string

Returns an instance of `MattyG\Handlebars\Template` - call render() on the template object (or use it as a callable) to render it.

#### Example

[](#example)

```
$template = $handlebars->compile('{{foo}} {{bar}}');
echo $template->render(array('foo' => 'FOO', 'bar' => 'BAR'));
// result: 'FOO BAR'
```

### registerHelper

[](#registerhelper)

Register a helper to be used within templates.

Helpers can return an instance of the SafeString class to ensure that the returned content is not escaped by the compiler.

Note that unlike the JS implementation of Handlebars, the concept of "this" is not bound to the current context inside of a helper. This is actually a freedom: it allows you to use any type of callable you wish.

#### Usage

[](#usage-1)

```
$handlebars->registerHelper(string $name, callable $helper);
```

#### Parameters

[](#parameters-1)

- `string $name` - the name of the helper
- `callable $helper` - the helper handler

#### Example

[](#example-1)

```
$handlebars->registerHelper('baz', function() { return 'BAZ&BAZ'; });
$template = $handlebars->compile('{{foo}} {{baz}}');
echo $template(array('foo' => 'FOO'));
// result: 'FOO BAZ&amp;BAZ'
```

```
use MattyG\Handlebars\SafeString;
$handlebars->registerHelper('safehelper', function($value) { return new SafeString($value . '&BAZ'); });
$template = $handlebars->compile('{{foo}} {{safehelper 'BAR'}}');
echo $template->render(array('foo' => 'FOO'));
// result: 'FOO BAR&BAZ'
```

### registerPartial

[](#registerpartial)

Registers a reusable partial template for use within other templates

#### Usage

[](#usage-2)

```
$handlebars->registerPartial(string $name, string $partial);
```

#### Parameters

[](#parameters-2)

- `string $name` - the name of the partial
- `string $partial` - the template string of the partial

#### Example

[](#example-2)

```
$handlebars->registerPartial('zoo', '1 + 2');
$template = $handlebars->compile('{{> zoo}} = {{result}}');
echo $template->render(array('result' => 3));
// result: '1 + 2 = 3'
```

### setCachePath

[](#setcachepath)

Enables caching of compiled templates.

#### Usage

[](#usage-3)

```
$handlebars->setCachePath(string $cachePath);
```

#### Parameters

[](#parameters-3)

- `string $cachePath` - The path to store cached copies of compiled templates

#### Example

[](#example-3)

```
$handlebars->setCachePath('/path/to/cache/folder');
```

### setNamePrefix

[](#setnameprefix)

Sets the name prefix for compiled templates. This is used to avoid conflicts when generating templates.

#### Usage

[](#usage-4)

```
$handlebars->setNamePrefix(string $namePrefix);
```

#### Parameters

[](#parameters-4)

- `string $namePrefix` - Custom prefix name

#### Example

[](#example-4)

```
$handlebars->setNamePrefix('special-template-');

```

Contributing
------------

[](#contributing)

All contributions are welcome. Ideally, all code contributions will come with new or updated tests :)

###  Health Score

33

—

LowBetter than 75% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity26

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity62

Established project with proven stability

 Bus Factor1

Top contributor holds 100% 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 ~82 days

Total

5

Last Release

3282d ago

Major Versions

6.1.0 → 7.0.02016-08-11

PHP version history (2 changes)6.0.0PHP &gt;=7.0.0

7.0.0PHP &gt;=7.0.8

### Community

Maintainers

![](https://www.gravatar.com/avatar/29e8622a72b856256e1b0f9e5ba9480444c6391e6e80a48eeb52fc4118eacf06?d=identicon)[djmattyg007](/maintainers/djmattyg007)

---

Top Contributors

[![djmattyg007](https://avatars.githubusercontent.com/u/489338?v=4)](https://github.com/djmattyg007 "djmattyg007 (114 commits)")

---

Tags

handlebarstemplate-enginetemplatetemplatinghandlebars

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/djmattyg007-handlebars/health.svg)

```
[![Health](https://phpackages.com/badges/djmattyg007-handlebars/health.svg)](https://phpackages.com/packages/djmattyg007-handlebars)
```

###  Alternatives

[eftec/bladeone

The standalone version Blade Template Engine from Laravel in a single php file

8208.4M87](/packages/eftec-bladeone)[zordius/lightncandy

An extremely fast PHP implementation of handlebars ( http://handlebarsjs.com/ ) and mustache ( http://mustache.github.io/ ).

60910.5M45](/packages/zordius-lightncandy)[fenom/fenom

Fenom - excellent template engine for PHP

44395.5k19](/packages/fenom-fenom)[duncan3dc/blade

Use Laravel Blade templates without the full Laravel framework

160499.5k24](/packages/duncan3dc-blade)[salesforce/handlebars-php

Handlebars processor for php

80713.2k11](/packages/salesforce-handlebars-php)[voodoophp/handlebars

Handlebars processor for php

34158.9k2](/packages/voodoophp-handlebars)

PHPackages © 2026

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