yuanqing / interpolate
Simple string interpolation in PHP.
Requires
- php: >=5.3
This package is not auto-updated.
Last update: 2020-01-20 03:23:58 UTC
README
A small PHP package for interpolating values from an array into a template string.
Think of it as a lightweight alternative to Mustache:
use yuanqing\Interpolate\Interpolate; $i = new Interpolate; $tmpl = '{{ foo.bar }}, {{ foo.baz }}!'; $data = array( 'foo' => array( 'bar' => 'Hello', 'baz' => 'World' ) ); $i->render($tmpl, $data); #=> 'Hello, World!'
Usage
-
Tags are enclosed in double braces.
-
Straight-up substitution; there are no conditional blocks, sections and so forth.
-
Tags can reference nested values in the multidimensional array (as in the example above).
-
A value to be interpolated can be a scalar, an object that implements
__toString()
, or a callback that returns a string:$i = new Interpolate; $tmpl = '{{ baz }}'; $data = array( 'foo' => 'Hello', 'bar' => 'World', 'baz' => function($data) { return sprintf('%s, %s!', $data['foo'], $data['bar']); } ); $i->render($tmpl, $data); #=> 'Hello, World!'
Note that the first argument of the callback is the
$data
array. -
If a value for a tag is not found, the tag will be replaced with an empty string.
The two examples in this README may be found in the examples.php file.
Requirements
Interpolate.php requires at least PHP 5.3, or HHVM.
Installation
Install with Composer
-
Install Composer.
-
Install the Interpolate.php Composer package:
$ composer require yuanqing/interpolate ~1.2
-
In your PHP, require the Composer autoloader:
require_once __DIR__ . '/vendor/autoload.php';
Install manually
-
Clone this repository:
$ git clone https://github.com/yuanqing/interpolate
Or just grab the zip.
-
In your PHP, require Interpolate.php:
require_once __DIR__ . '/src/Interpolate.php';
Testing
You need PHPUnit to run the tests:
$ git clone https://github.com/yuanqing/interpolate
$ cd interpolate
$ phpunit
License
MIT license