PHPackages                             nicmart/string-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. nicmart/string-template

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

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.

v0.1.3(3y ago)2101.7M↓19.3%30[1 PRs](https://github.com/nicmart/StringTemplate/pulls)20MITPHPPHP &gt;=7.2

Since Nov 4Pushed 3y ago8 watchersCompare

[ Source](https://github.com/nicmart/StringTemplate)[ Packagist](https://packagist.org/packages/nicmart/string-template)[ RSS](/packages/nicmart-string-template/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (2)Dependencies (2)Versions (5)Used By (20)

StringTemplate
==============

[](#stringtemplate)

[![Build Status](https://github.com/nicmart/StringTemplate/actions/workflows/php.yml/badge.svg?branch=master)](https://github.com/nicmart/StringTemplate/actions/workflows/php.yml)[![Packagist](https://camo.githubusercontent.com/ec7d21d7df2cc246504eb211b8b2bac7d0cbc69b1a448622fd757425f58ef8da/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6e69636d6172742f737472696e672d74656d706c6174652e737667)](https://packagist.org/packages/nicmart/string-template/stats)[![Packagist](https://camo.githubusercontent.com/83d1ca51f6cd2934514aa26a23bea34a8dcdc0965dac9cf1d2c7effad4b3f8d2/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f646d2f6e69636d6172742f737472696e672d74656d706c6174652e737667)](https://packagist.org/packages/nicmart/string-template/stats)

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 substitutions.

For installing instructions, go to the end of this README.

Why
---

[](#why)

I have often struggled against sprintf's lack of a named placeholders feature, so I have decided to write once and for all a simple component that allows you to render a template string in which placeholders are named.

Furthermore, its placeholders can be nested as much as you want (multidimensional arrays allowed).

Usage
-----

[](#usage)

Simply create an instance of `StringTemplate\Engine`, and use its `render` method.

Placeholders are delimited by default by `{` and `}`, but you can specify others through the class constructor.

```
$engine = new StringTemplate\Engine;

//Scalar value: returns "This is my value: nic"
$engine->render("This is my value: {}", 'nic');
```

You can also provide an array value:

```
//Array value: returns "My name is Nicolò Martini"
$engine->render("My name is {name} {surname}", ['name' => 'Nicolò', 'surname' => 'Martini']);
```

Nested array values are allowed too! Example:

```
//Nested array value: returns "My name is Nicolò and her name is Gabriella"
$engine->render(
    "My name is {me.name} and her name is {her.name}",
    [
        'me' => ['name' => 'Nicolò'],
        'her' => ['name' => 'Gabriella']
    ]);
```

Object values will be converted to strings:

```
class Foo { function __toString() { return 'foo'; }

//Returns "foo: bar"
$engine->render(
    "{val}: bar",
    ['val' => new Foo]);
```

You can change the delimiters as you want:

```
$engine = new StringTemplate\Engine(':', '');

//Returns I am Nicolò Martini
$engine->render(
    "I am :name :surname",
    [
        'name' => 'Nicolò',
        'surname' => 'Martini'
    ]);
```

### SprintfEngine

[](#sprintfengine)

You can use a more powerful version of the engine if you want to specify [convertion specifications](http://php.net/manual/en/function.sprintf.php) for placeholders. The conversion syntax is identical to `sprintf` one, you need only to specify the optional parameter after the placeholder name.

Example:

```
$engine = new StringTemplate\SprintfEngine;

//Returns I have 1.2 (1.230000E+0) apples.
   $engine->render(
       "I have {num%.1f} ({num%.6E}) {fruit}.",
       [
           'num' => 1.23,
           'fruit' => 'apples'
       ]
   )
```

Keep in mind that power comes at a cost: `SprintfEngine` is 3 times slower than `Engine`(although if there are no '%' in the template string then performance is almost the same).

NestedKeyIterator and NestedKeyArray
------------------------------------

[](#nestedkeyiterator-and-nestedkeyarray)

Internally the engine iterates through the value array with the `NestedKeyIterator`. `NestedKeyIterator`iterates through multi-dimensional arrays giving as key the imploded keys stack.

It can be useful even if you don't need the Engine. Keep in mind that it is an `RecursiveIteratorIterator`, and so you have to pass a `RecursiveIterator` to its constructor (or, better, a `StringTemplate\RecursiveArrayOnlyIterator` if you do not want to iterate through objects).

Example:

```
use StringTemplate\NestedKeyIterator;
use StringTemplate\RecursiveArrayOnlyIterator;

$ary = [
    '1' => 'foo',
    '2' => [
        '1' => 'bar',
        '2' => ['1' => 'fog']
    ],
    '3' => [1, 2, 3]
];

$iterator = new NestedKeyIterator(new RecursiveArrayIterator($ary));

foreach ($iterator as $key => $value)
    echo "$key: $value\n";

// Prints
// 1: foo
// 2.1: bar
// 2.2.1: fog
// 3.0: 1
// 3.1: 2
// 3.2: 3
```

### NestedKeyArray

[](#nestedkeyarray)

In addition to iteration with nested keys, the library offers a class that allows you to access a multidimensional array with flatten nested keys as the ones seen above. It's called `NestedKeyArray`.

Example:

```
use StringTemplate\NestedKeyArray;

$ary = [
    '1' => 'foo',
    '2' => [
        '1' => 'bar',
        '2' => ['1' => 'fog']
    ],
    '3' => [1, 2, 3]
];

$nestedKeyArray = new NestedKeyArray($ary);

echo $nestedKeyArray['2.1']; //Prints 'bar'
$nestedKeyArray['2.1'] = 'new bar';
unset($nestedKeyArray['2.2']);
isset($nestedKeyArray['2.1']); //Returns true

foreach ($iterator as $key => $value)
    echo "$key: $value\n";

// Prints
// 1: foo
// 2.1: new bar
// 3.0: 1
// 3.1: 2
// 3.2: 3
```

Where is it used
----------------

[](#where-is-it-used)

I use StringTemplate in [DomainSpecificQuery](https://github.com/comperio/DomainSpecificQuery)to implement the `Lucene\TemplateExpression` class.

Install
-------

[](#install)

The best way to install StringTemplate is [through composer](http://getcomposer.org).

Just create a composer.json file for your project:

```
{
    "require": {
        "nicmart/string-template": "~0.1"
    }
}
```

Then you can run these two commands to install it:

```
$ curl -s http://getcomposer.org/installer | php
$ php composer.phar install

```

or simply run `composer install` if you have have already [installed the composer globally](http://getcomposer.org/doc/00-intro.md#globally).

Then you can include the autoloader, and you will have access to the library classes:

```
