PHPackages                             neoan3-apps/template - 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. neoan3-apps/template

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

neoan3-apps/template
====================

PHP DOMDocument-based minimal template engine

v2.1.6(3y ago)330.9k1[1 PRs](https://github.com/sroehrl/neoan3-template/pulls)7MITPHPCI passing

Since Feb 2Pushed 4w ago1 watchersCompare

[ Source](https://github.com/sroehrl/neoan3-template)[ Packagist](https://packagist.org/packages/neoan3-apps/template)[ RSS](/packages/neoan3-apps-template/feed)WikiDiscussions master Synced 4d ago

READMEChangelog (10)Dependencies (1)Versions (33)Used By (7)Security (1)

neoan3-apps/template
====================

[](#neoan3-appstemplate)

PHP template engine

[![Test Coverage](https://camo.githubusercontent.com/26ed9a5715c11f5dd03c9cea09ed733c807f2fa7ccdcd4f8effbc6df15a08b38/68747470733a2f2f6170692e636f6465636c696d6174652e636f6d2f76312f6261646765732f37366230393932343330303337356334643739612f746573745f636f766572616765)](https://codeclimate.com/github/sroehrl/neoan3-template/test_coverage)[![Maintainability](https://camo.githubusercontent.com/973124afd151219846268b0e8147172ed51a52b356ab0a3863d8baa14c730c14/68747470733a2f2f6170692e636f6465636c696d6174652e636f6d2f76312f6261646765732f37366230393932343330303337356334643739612f6d61696e7461696e6162696c697479)](https://codeclimate.com/github/sroehrl/neoan3-template/maintainability)[![Build Status](https://camo.githubusercontent.com/85077dffbdf506385ed77f598cfdb1a6d3e30b70fef8b3f74faf033f3eefcaa2/68747470733a2f2f7472617669732d63692e6f72672f73726f6568726c2f6e656f616e332d74656d706c6174652e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/sroehrl/neoan3-template)

> As of version 2, we dropped PHP 7.4 support. You require at least PHP 8.0 or use v1.2.0 of this package.

Installation / Quick start
--------------------------

[](#installation--quick-start)

`composer require neoan3-apps/template`

```
use Neoan3\Apps\Template\Constants;
use Neoan3\Apps\Template\Template;

require_once 'vendor/autoload.php';

// optional, if set, path defines the relative starting point to templates
Constants::setPath(__DIR__ . '/templates');

echo Template::embrace('{{test}}',['test'=>'Hello World']);
```

Contents
--------

[](#contents)

- [Templating](#templating)
- [Iterations](#iterations-n-for)
- [Conditions](#conditions-n-if)
- [Custom Functions](#custom-functions)
- [Custom Delimiter](#custom-delimiter)
- [Custom Attributes](#custom-attributes)
- [OOP](#oop)
- [Tips](#tips)

Templating
----------

[](#templating)

**neoan3-template** is not a full blown template engine, but rather what a template engine should be: With modern JavaScript solutions creating a dynamic approach, neoan3-template focuses on the necessities of static rendering.

*profile.html*

```
{{user}}
{{profile.name}}
{{item}}-{{key}}
```

*profile.php*

```
$dynamicContent = [
    'user' => 'Test',
    'items' => ['one','two'],
    'profile' => [
        'name' => 'John Doe',
        ...
    ]
];
echo \Neoan3\Apps\Template\Template::embraceFromFile('profile.html',$dynamicContent);
```

*output*

```
Test
John Doe
two-1
```

### Main templating methods

[](#main-templating-methods)

#### embrace($string, $substitutionArray)

[](#embracestring-substitutionarray)

Replaces array-keys indicated by double curly braces with the appropriate value

#### embraceFromFile($fileLocation, $substitutionArray)

[](#embracefromfilefilelocation-substitutionarray)

Reads content of a file and executes the embrace function.

Iterations (n-for)
------------------

[](#iterations-n-for)

The n-for loop evaluates as PHP's foreach and uses the same syntax (excluding the $-sign). In order to access keys, use the PHP markup (items as key =&gt; value) to emulate $items as $key =&gt; $value. Without the necessity to access keys, use the simple markup items =&gt; item.

```
$parameters = [
    'items' => ['one', 'two']
];
$html = '{{item}}';
echo \Neoan3\Apps\Template::embrace($html, $parameters);
```

Output:

```
one
two
```

Conditions (n-if)
-----------------

[](#conditions-n-if)

You can attach the n-if attribute to any tag in order to render conditionally. Curly braces are not required and nesting follows the same rules as general rendering (meaning that you will write `outer.inner` to access `$parameters['outer']['inner']`)

n-if is type conscious and therefore evaluates strict.

truefalsefalse == 'false'false === 'false'Conditions work in nested context and inherit naming.

Example within n-for:

```
$parameters = [
    'items' => ['one', 'two']
];
$html = '{{item}}';
echo \Neoan3\Apps\Template::embrace($html, $parameters);
```

Output:

```

two
```

Custom functions
----------------

[](#custom-functions)

Unlike other template engines, **neoan3-apps/template** does not come with expensive additional functionality. It is our believe that most of what other template engines offer should not be included in a template engine. However, you can pass in custom closures to achieve custom transformation or similar.

Example:

```
$html = '{{headline(items.length)}}{{toUpper(item)}}';

$passIn = [
    'items'=>['chair', 'table']
];
// pluralize
\Neoan3\Apps\Template\Constants::addCustomFunction('headline', function ($input){
    return $input . ' item' . ($input>1 ? 's' : '');
});
// transform uppercase
\Neoan3\Apps\Template\Constants::addCustomFunction('toUpper', function ($input){
    return strtoupper($input);
});
echo \Neoan3\Apps\Template::embrace($html, $passIn);
```

Output:

```
2 items
CHAIR
TABLE
```

You can even use substitutions like this (as used in [php-i18n-translate](https://github.com/sroehrl/php-i18n-translate#readme)):

```
The current rating is {{rating [%format](% {{% round(percentage) %)}}
```

```
$data = [
 'percentage' => 8,332,
 'rating [%format%]'
];
\Neoan3\Apps\Template\Constants::addCustomFunction('round', function ($input){
    return round((float)$input) . '%';
});
echo \Neoan3\Apps\Template::embraceFromFile('/aboveHtml.html', $data);
```

Output:

```
The current rating is 8%
```

Custom delimiter
----------------

[](#custom-delimiter)

There is a reason why curly braces are used: You can leverage the fact that some values are only potentially filled by the backend and addressed in the front-end if the value does not exist in your data (yet). However, there are also cases where you want to specifically avoid having your front-end framework picking up unfilled variables, or you have special parsing needs to work with various files. Therefore, you can use custom identifiers by providing your desired markup to **embrace** or **embraceFromFile**.

Example:

```
$html = '
[[name]]
Here is content
';

$substitutions = [
    'name' => 'neoan3'
];
// characters are escaped automatically
\Neoan3\Apps\Template\Constants::setDelimiter('[[',']]');

echo \Neoan3\Apps\Template\Template::embrace($html, $substitutions);
```

Output:

```
neoan3
Here is content
```

**NOTE:** If your delimiter is a tag, the engine will **NOT** remove the delimiter:

```
use \Neoan3\Apps\Template\Constants;
use \Neoan3\Apps\Template\Template;

Constants::setDelimiter('','');

$esperanto = [
    'hello' => 'saluton'
];

$user => ['userName' => 'Sammy', ...];

$html = "hello {{userName}}";

$translated = Template::embrace($html, $esperanto);

Constants::setDelimiter('{{','}}');

echo Template::embrace($translated, $user);
```

Output:

```
salutaton Sammy
```

Custom Attributes
-----------------

[](#custom-attributes)

Under the hood, n-if and n-for are just custom attributes. You can add your own attributes and extend the engine to your needs using any callable:

```
use \Neoan3\Apps\Template\Constants;

class TranslateMe
{
    private string $language;

    // you will receive the native DOMAttr from DOMDocument
    // and the user-provided array
    function __invoke(\DOMAttr &$attr, $contextData = []): void
    {
        // here we are going to use the "flat" version of the context data
        // it translates something like
        // ['en' => ['hallo'=>'hello']] to ['en.hallo' => 'hello]
        $flatValues = Constants::flattenArray($contextData[$this->language]);

        // if we find the content of the actual element in our translations:
        if(isset($flatValues[$attr->parentNode->nodeValue])){
            $attr->parentNode->nodeValue = $flatValues[$attr->parentNode->nodeValue];
        }
    }
    function __construct(string $lang)
    {
        $this->language = $lang;
    }
}
```

```

hallo
```

```
use \Neoan3\Apps\Template\Constants;
use \Neoan3\Apps\Template\Template;
...
$translations = [
    'en' => [
        'hallo' => 'hello',
        ...
    ],
    'es' => [
        'hallo' => 'hola',
        ...
    ]
];

$userLang = 'en';

Constants::addCustomAttribute('translate', new TranslateMe($userLang));
echo Template::embraceFromFile('/main.html', $translations)
```

OOP
---

[](#oop)

So far, we have used a purely static approach. However, the "Template" methods are merely facades resulting in the initialization of the Interpreter. If you need more control over what is happening, or it better fits your situation, you are welcome to use it directly:

```
$html = file_get_contents(__DIR__ . '/test.html);

$contextData = [
    'my' => 'value'
];
$templating = new \Neoan3\Apps\Template\Interpreter($html, $contextData);

// at this point, nothing is parsed or set if we wanted to use the attributes n-if or n-for, we would have to set it
// note how we are free to change the naming now

\Neoan3\Apps\Template\Constants::addCustomAttribute('only-if', new \Neoan3\Apps\Attributes\NIf());

// Let's parse in one step:
$templating->parse();

// And output

echo $templating->asHtml();
```

Tips
----

[](#tips)

There are a few things that are logical, but not obvious:

### Parents on loops

[](#parents-on-loops)

Due to processing in hierarchy, many internal parsing operations can cause race-conditions. Imagine the following HTML:

```
// ['items' => ['one','two'], 'name' => 'John']

    {{item}} {{name}}
    {{name}}

```

In this scenario, the parser would first hit the attribute `n-for`and add p-tags to the parent node (here div). `n-for` now takes control of this parent and interprets the children. As the context gets reevaluated in every loop, but the second p-tag is not iterated, the resulting output would be:

```

    {{name}}
    one John
    two John

```

It is therefore recommended to use **one** distinct parent when using attribute methods:

```
// ['items' => ['one','two'], 'name' => 'John']

    {{item}} {{name}}

    {{name}}

```

### Flat array properties

[](#flat-array-properties)

The interpreter "flattens" the given context-array in order to allow for the dot-notation. In this process generic values are added:

```
// ['items' => ['one','two'], 'deepAssoc' => ['name' => 'Tim']]
{{items}}
{{items.0}}
{{items.length}}
{{deepAssoc.name}}
```

output:

```
Array
one
2
Tim
```

If needed, you can use this in logic:

```

        {{item}}

```

###  Health Score

46

—

FairBetter than 93% of packages

Maintenance62

Regular maintenance activity

Popularity27

Limited adoption so far

Community15

Small or concentrated contributor base

Maturity68

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 ~64 days

Recently: every ~39 days

Total

18

Last Release

1208d ago

Major Versions

1.2.0 → 2.0.02022-08-15

### Community

Maintainers

![](https://www.gravatar.com/avatar/92d2361b646651e3452a62d07274076346c4096480098a6c43d6c27ee28d460d?d=identicon)[neoan](/maintainers/neoan)

---

Top Contributors

[![sroehrl](https://avatars.githubusercontent.com/u/28542911?v=4)](https://github.com/sroehrl "sroehrl (87 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/neoan3-apps-template/health.svg)

```
[![Health](https://phpackages.com/badges/neoan3-apps-template/health.svg)](https://phpackages.com/packages/neoan3-apps-template)
```

###  Alternatives

[mustache/mustache

A Mustache implementation in PHP.

3.3k44.6M291](/packages/mustache-mustache)[roots/acorn

Framework for Roots WordPress projects built with Laravel components.

9682.1M97](/packages/roots-acorn)[whitecube/nova-flexible-content

Flexible Content &amp; Repeater Fields for Laravel Nova.

8053.0M25](/packages/whitecube-nova-flexible-content)[mopa/bootstrap-bundle

Easy integration of twitters bootstrap into symfony2

7042.9M33](/packages/mopa-bootstrap-bundle)[limenius/react-bundle

Client and Server-side react rendering in a Symfony Bundle

3871.2M](/packages/limenius-react-bundle)[nicmart/string-template

StringTemplate is a very simple string template engine for php. I've written it to have a thing like sprintf, but with named and nested substutions.

2101.7M30](/packages/nicmart-string-template)

PHPackages © 2026

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