• Stars
    star
    200
  • Rank 195,325 (Top 4 %)
  • Language
    PHP
  • License
    MIT License
  • Created over 11 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A death-simple string templating engine for php.

StringTemplate

Build Status Packagist Packagist

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

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

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

You can use a more powerful version of the engine if you want to specify convertion specifications 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

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

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

I use StringTemplate in DomainSpecificQuery to implement the Lucene\TemplateExpression class.

Install

The best way to install StringTemplate is through composer.

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.

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

<?php
require 'vendor/autoload.php';

More Repositories

1

Tree

A basic but flexible tree data structure for php and a fluent tree builder implementation.
PHP
546
star
2

Numbers

Transform numbers in various formats, like scientific notation or unit-suffix notation
PHP
54
star
3

UniversalMatcher

A rule based matcher engine for php.
PHP
28
star
4

Arrayze

Callback-based array adapter for PHP
PHP
25
star
5

Functionals

A set of functionals for PHP
PHP
23
star
6

Building

A PHP library that abstracts the definition of fluent builders.
PHP
16
star
7

Evolution

Functional Generative Drawing
Scala
15
star
8

Benchmark

A framework for benchmarking php code
PHP
13
star
9

DGIM

A PHP implementation of the DGIM algorithm to count a stream of ones in a window.
PHP
12
star
10

ExpressionTree

Build and dump ExpressionTrees
PHP
5
star
11

WeightedRandomDistribution

An implementation of the ALIAS method for Weighted Random Distributions
Scala
4
star
12

GetLocalization

Basic GetLocalization client for php
PHP
4
star
13

PhpLibraryBoilerplate

A basic template I use every time I create a new php library
PHP
4
star
14

PhpGenerics

Tools for generic type programming in php
PHP
4
star
15

RandomPainter

Generative Art experiments in Scala
Scala
3
star
16

Phpy

An experimental libarary for php code inspection and generation
PHP
2
star
17

Demiurge

A library for object creation
PHP
2
star
18

CoversCarousel

A death simple, mobile friendly, covers carousel plugin for jQuery
JavaScript
2
star
19

Finga

Finga is a open source PHP library for fingerprinting php values.
PHP
2
star
20

Rulez

A blazing fast rules engine for PHP
PHP
2
star
21

SearchConfig

An example of DomainSpecificQuery compiler configuration
PHP
2
star
22

DomainSpecificQuery

Build and define queries specific to the application domain and compile them into other formats
PHP
2
star
23

Babylon-Crawler

Scala
1
star
24

Markov

Text shuffler
Scala
1
star
25

LiveTerminal

A simple tool that helps writing live data to the terminal
PHP
1
star
26

TreeBuilder

A library for tree transforming
PHP
1
star
27

HierarchicalClustering

Hierarchical Clustering Library for PHP
PHP
1
star
28

ChurchScala

Church type encodings in Scala
Scala
1
star
29

RandoXML

A PHP Library whose aim is to generate XML documents in a random way, following probabilistic rules defined in a configuration file
PHP
1
star