PHPackages                             aleksandr.ru/template-object - 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. aleksandr.ru/template-object

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

aleksandr.ru/template-object
============================

Another simple template parser

2.7(2y ago)03.8k↓33.3%MITPHPPHP &gt;=5.3.0

Since Oct 2Pushed 2y ago1 watchersCompare

[ Source](https://github.com/Aleksandr-ru/TemplateObject)[ Packagist](https://packagist.org/packages/aleksandr.ru/template-object)[ Docs](https://github.com/Aleksandr-ru/TemplateObject)[ RSS](/packages/aleksandrru-template-object/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)DependenciesVersions (3)Used By (0)

TemplateObject
==============

[](#templateobject)

Another simple template parser. Also available via composer:

```
composer require aleksandr.ru/template-object

```

### Features

[](#features)

- Blocks of markup as object
- Block repeat (setBlock appends new block and returns handle to it)
- Recursive blocks (see example below)
- Empty block placeholders
- Independent variables in blocks and main template
- Variable data escaping (filtering) in template, see markup below
- Variable filtering manipulation: add, replace, remove custom filters
- Includes and protection against recursive includes
- Extending templates and protection against recursive extending

Markup example
--------------

[](#markup-example)

*header.html*

```

	{{TITLE|raw}}

		alert('{{TITLE|js}}');

```

*page.html*

```

{{TITLE}}

	Column-1
	Column-2

	{{COL1}}
	{{COL2}}

	No data

```

*footer.html*

```
{{MULTILINE|html|nl2br}}

```

Code example
------------

[](#code-example)

*in case of not usage the 'row' block, content of EMPTY will be shown*

```
// WARNING! Since 2.0 the loadTemplate become static and return TemplateObject
// this syntax is not valid any more
// $to = new TemplateObject();
// $to->loadTemplate('page.html');
// Please use following
$to = TemplateObject::loadTemplate('page.html');
$to->setVariable('TITLE', 'this is a title');
for($i=1; $isetBlock('row');
	$row->setVariable('COL1', $i);
	$row->setVariable('COL2', "test-$i");
}
$string = "String with \"quotes\" and several lines\n second line\n thitd line";
$to->setVariable('MULTILINE', $string);
$to->showOutput();

```

Extending templates
-------------------

[](#extending-templates)

Since 2.0 there is an abilty to extend templates. For example:

*yeild.html*

```

	{{TITLE}}

			This content will be yeilded

			This content will be yeilded

			This content will be yeilded

```

*extend.html*

```

	This is the header

	This is the content

		Column-1
		Column-2

		{{COL|html}}
		{{COL|raw}}

		No data

	This is the footer

```

The code is the same:

```
$to = TemplateObject::loadTemplate('extend.html');
$to->setVariable('TITLE', "this is a 'title'");
for($i=1; $isetBlock('row');
    $row->setVariable('COL', "test \"$i\"");
}
$to->showOutput();

```

Recursive blocks
----------------

[](#recursive-blocks)

Since 2.4 there is an abilty to make your blocks recursive. For example:

*recursive.html*

```

	[a recursive block]

```

The code:

```
$to = TemplateObject::loadTemplate('recursive.html');
$to->setBlock('blockname')->setBlock('blockname')->setBlock('blockname');
$to->showOutput();

```

Output:

```
[a recursive block] [a recursive block] [a recursive block]

```

Function quick reference
------------------------

[](#function-quick-reference)

### *static* loadTemplate(string $file) : TemplateObject

[](#static-loadtemplatestring--file--templateobject)

Load template from file.

### \_\_construct(string $data = '', string $base\_dir = '')

[](#__constructstring--data---string--base_dir--)

Constructor.

### \_\_destruct()

[](#__destruct)

Free and reset resources.

### getBlocks() : array

[](#getblocks--array)

Returns all blocks found in the template. Only 1st level of blocks are returned, not recursive.

### getVariables() : array

[](#getvariables--array)

Returns all variables found in template. Only variables outside of blocks are returned.

### setBlock(string $blockname) : TemplateObject

[](#setblockstring--blockname--templateobject)

Set block for usage (add a new block to markup and return handle).

### setGlobalVariable(string $var, string $val) : boolean

[](#setglobalvariablestring--var-string--val--boolean)

Set a variable in global scope.

### setVariable(string $var, string $val) : boolean

[](#setvariablestring--var-string--val--boolean)

Set the variable in markup. Triggers E\_USER\_NOTICE if variable was not found.

### setVarArray(array $arr)

[](#setvararrayarray--arr)

Set variables from an array like

```
array(
'VAR1' => 'value',
'VAR2' => 'another value',
'singleblock' => array('BLOCKVAR1' => 'value1', 'BLOCKVAR2' => 'value2', ...),
'multiblock' => array(
    [0] => array('VAR1' => 'val1', 'VAR2' => 'val2'),
    [1] => array('VAR1' => 'val3', 'VAR2' => 'val4'),
),
'emptyblock' => NULL,
...)

```

### getOutput() : string

[](#getoutput--string)

Get parsed template with all data set.

### showOutput()

[](#showoutput)

Print parsed template with all data set.

### addFilter(string $filter, callable $callback, boolean $overwrite = FALSE) : boolean

[](#addfilterstring--filter-callable--callback-boolean--overwrite--false--boolean)

Add (or replace) a filer for variables. Triggers E\_USER\_NOTICE if filter already exists and no $overwrite. Triggers E\_USER\_NOTICE when given $callback is not callable.

### removeFilter(string $filter) : boolean

[](#removefilterstring--filter--boolean)

Remove an existing filter. Triggers E\_USER\_NOTICE if filter does not exists.

### getForcedFilter() : string

[](#getforcedfilter--string)

Since 2.7. Get current forced filter.

### setForcedFilter(string $filter) : boolean

[](#setforcedfilterstring--filter--boolean)

Since 2.7. Set new forced filer. By default, is set to "html". Triggers E\_USER\_WARNING if filter does not exist.

Forced filter is filter to be applied first if there is no "raw" filter and no same filter is set for variable. Forced filter can contain several elements like `html|nl2br`, each will be prepended to variable's filters, if is not set.

This mechanism may cause some backwards compatibility issues: before 2.7 `{{VAR}}` means `{{VAR|html}}` and `{{VAR|js}}` means only `{{VAR|js}}` (no html applied), since 2.7 `{{VAR}}` means `{{VAR|html}}` and `{{VAR|js}}` means `{{VAR|html|js}}` (html is forcefully prepended). To get back old behaviour of `{{VAR|js}}` you need to add "raw" filter like `{{VAR|raw|js}}`.

More documentation
------------------

[](#more-documentation)

See PhpDoc in code.

Version history
---------------

[](#version-history)

- 2.7 Forced filter instead of default, applies until raw is set
- 2.6 Removed side effect of preserving blocks by setting it to a non-assoc array
- 2.5 Template processing boost and new option `public $debug = false`
- 2.4 Recursive blocks via new markup ``
- 2.3 Preserve empty blocks in setVarArray via `'emptyblock' => NULL`
- 2.2 Block options: `` this blocks will be outputted in reversed order, see BLOCKOPTION\_\* constants
- 2.1 Global variables: inherited to all child blocks
- 2.0 Now one template can extend another template by replacing it's blocks with own content
- 1.3 Ability to get variables and blocks from loaded template
- 1.2 Multiple filter support like `{{VAR|html|nl2br}}`
- 1.1 Added filter support for variables `{{VAR|raw}}` `{{VAR|html}}` `{{VAR|js}}`
- 1.0 Initial

###  Health Score

27

—

LowBetter than 49% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity20

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity50

Maturing project, gaining track record

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

Total

2

Last Release

1082d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/08f455fb3a3af0784f4353b0977f11b1b6c0fd7e97ab9eb3394b2ea9a84d453c?d=identicon)[aleksandr.ru](/maintainers/aleksandr.ru)

---

Top Contributors

[![Aleksandr-ru](https://avatars.githubusercontent.com/u/15122148?v=4)](https://github.com/Aleksandr-ru "Aleksandr-ru (19 commits)")

---

Tags

php-librarytemplate-parserparsertemplaterecursive

### Embed Badge

![Health badge](/badges/aleksandrru-template-object/health.svg)

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

###  Alternatives

[phpoffice/phpword

PHPWord - A pure PHP library for reading and writing word processing documents (OOXML, ODF, RTF, HTML, PDF)

7.5k34.7M186](/packages/phpoffice-phpword)[rize/uri-template

PHP URI Template (RFC 6570) supports both expansion &amp; extraction

420137.3M46](/packages/rize-uri-template)[pyrocms/lex

A lightweight template parser.

11128.3k2](/packages/pyrocms-lex)

PHPackages © 2026

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