PHPackages                             miladrahimi/phptemplate - 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. miladrahimi/phptemplate

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

miladrahimi/phptemplate
=======================

Free PHP template engine for neat and powerful projects!

1.0(10y ago)337MITPHPPHP &gt;=5.3.0

Since Jul 31Pushed 7y ago3 watchersCompare

[ Source](https://github.com/miladrahimi/phptemplate)[ Packagist](https://packagist.org/packages/miladrahimi/phptemplate)[ Docs](http://github.com/miladrahimi/phptemplate)[ RSS](/packages/miladrahimi-phptemplate/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (1)DependenciesVersions (2)Used By (0)

PHPTemplate
===========

[](#phptemplate)

A PHP template engine!

Overview
--------

[](#overview)

Modern application architectures follow user interface and logic segregation. Application logic layer provides information to display in user interface layer. Thus, the user interface (view) will be separated from logic layer (controller).

Template Engines offer structured solution to implement this segregation. Let's see!

User Interfaces are template files which include static (HTML) and dynamic parts. Dynamic parts are the places which Template Engine put information there. Controller pass information and template name to Template Engine. Template Engine returns compiled template (ultimate HTML). The controller send the result to the user.

PHPTemplate syntax is the best syntax for HTML, XML and tag based documents. It is designed smartly to be pretty while web designers design.

### Installation

[](#installation)

#### Using Composer (Recommended)

[](#using-composer-recommended)

Read [How to use composer in php projects](http://miladrahimi.com/blog/2015/04/12/how-to-use-composer-in-php-projects)article if you are not familiar with [Composer](http://getcomposer.org).

Run following command in your project root directory:

```
composer require miladrahimi/phptemplate

```

#### Manually

[](#manually)

You may use your own autoloader as long as it follows [PSR-0](http://www.php-fig.org/psr/psr-0) or [PSR-4](http://www.php-fig.org/psr/psr-4) standards. Just put `src` directory contents in your vendor directory.

### Getting Started

[](#getting-started)

Following example shows how to render `profile.html` template file.

A simple template file example:

```
use MiladRahimi\PHPTemplate\TemplateEngineFactory;

$te = TemplateEngineFactory::create();
$te->setBaseDirectory("../Views");

$data = array(
    "name"     => "Bon",
    "surname"  => "Jovi"
);

echo $te->render("profile.html", $data);

```

And the `profile.html` template file:

```

    User Profile

    Profile
    Welcome {name} {surname}!

```

### Phrases

[](#phrases)

Phrases are simple variables which will be filled by Template Engine based on given data. As the example above illustrates `{name}` and `{surname}` are phrase.

Phrases will be HTML-safe by PHP native `htmlspecialchars()` function. If you need raw data to be inserted like HTML snippets, put `!` after `{` character. See following example:

```
 {!content}

```

### Flexible Templates

[](#flexible-templates)

Phrases are used to display data in the view (template). But sometimes the data must be controlled or manipulated before displaying. Some data must not be displayed always, like "sign in" button when user is authenticated already. Some data must be repeated more than once, like posts in a blog homepage. PHPTemplate offers boolean and array tags to implement such cases.

### Boolean Tags

[](#boolean-tags)

Boolean tags are used to display content while the tag name as an element in the given data is true.

Let's extend the mentioned example:

```
use MiladRahimi\PHPTemplate\TemplateEngineFactory;

$te = TemplateEngineFactory::create();
$te->setBaseDirectory("../Views");

$data = array(
    "name"     => "Bon",
    "surname"  => "Jovi",
    "is-admin" => true
);

echo $te->render("profile.html", $data);

```

And the `profile.html` file:

```

    User Profile

    Profile
    Welcome {name} {surname}!
    You are admin!

```

In web design level, boolean tags will be displayed in the browser.

### Sequential Arrays

[](#sequential-arrays)

PHPTemplate HTML-like syntax for sequential arrays made using arrays so easy. Array can be implemented by tags just like booleans. The tag content will be repeated as much as array length. Just like a `foreach` loop in PHP, you need to define a name for current array element to use in the body. In PHPTemplate you can define this name by HTML-like `value` attribute.

```
use MiladRahimi\PHPTemplate\TemplateEngineFactory;

$te = TemplateEngineFactory::create();
$te->setBaseDirectory(__DIR__);

$data = array(
    "name"    => "David",
    "surname" => "Gilmour",
    "genres"  => array("Progressive Rock", "Art Rock", "Blues Rock")
);

echo $te->render("singer.html", $data);

```

And the `singer.html` template file:

```

    My Favorite Singer

    {name} {surname}
    Genres

        {item}

```

- `genres` tag content will be repeated as much as `genres` array length.
- You can access current element by set name in the `value` attribute, here `item`.
- In web design level, the array body will be displayed once.

### Associative Arrays

[](#associative-arrays)

Associative Arrays can be passed to template engine by its paired key/value without array container. Of course PHPTemplate still support it very well.

Associative arrays are pack of key/value elements. Just like a `foreach()` loop, you need to define two names, one for current key and one for current value.

In the following example, I have define `album` name for current key and `year` for current value.

```
use MiladRahimi\PHPTemplate\TemplateEngineFactory;

$te = TemplateEngineFactory::create();
$te->setBaseDirectory(__DIR__);

$data = array(
    "name"    => "David",
    "surname" => "Gilmour",
    "genres"  => array("Progressive Rock", "Art Rock", "Blues Rock"),
    "albums"  => array("On an Island" => 2006, "Rattle That Lock" => 2015)
);

echo $te->render("singer.html", $data);

```

And the `singer.html` template file:

```

    My Favorite Singer

    {name} {surname}
    Genres

        {item}

    Albums

        {album} : {year}

```

### Records

[](#records)

Records are associate array which you need to access its all the elements at once. Record concept is so useful in table designs. PHPTemplate let you access records as easy as a pie!

See the example and `singles` arrays which has some records:

```
use MiladRahimi\PHPTemplate\TemplateEngineFactory;

$te = TemplateEngineFactory::create();
$te->setBaseDirectory(__DIR__);

$data = array(
    "name"    => "David",
    "surname" => "Gilmour",
    "genres"  => array("Progressive Rock", "Art Rock", "Blues Rock"),
    "albums"  => array("On an Island" => 2006, "Rattle That Lock" => 2015),
    "singles" => array(
        array("track" => "There's No Way Out of Here", "album" => "David Gilmour"),
        array("track" => "Blue Light",                 "album" => "About Face"),
        array("track" => "Love on the Air",            "album" => "About Face")
    )
);

echo $te->render("singer.html", $data);

```

And the `singer.html` template file:

```

    My Favorite Singer

    {name} {surname}
    Genres

        {item}

    Albums

        {album} : {year}

    Singles

            {track} of the album {album}

```

- No need to define key and value for records.
- All record array keys will be accessible via phrases.
- It's a good feature for table design.

### Data types

[](#data-types)

PHPTemplate converts all data to strings or arrays.

All scalar data like strings, integers, floats, etc will be converted to string.

All objects which has `__toString()` method will be converted to strings.

All arrays and traversable objects will be converted to arrays.

All closures will be invoked and the returned value will be checked recursively.

If the data type is not convert-able to string or array, `BadDataException` will be thrown.

### Functions

[](#functions)

It's a good practice to avoid using logical directives in the view layer. However, you may still need to access your application APIs in the view layer. You can pass closures like other valid data types to the template engine. The passed closure must return a closure or a valid data type value to be processed and replaced in the phrase.

See the `date` element in the following example:

```
use MiladRahimi\PHPTemplate\TemplateEngineFactory;

$te = TemplateEngineFactory::create();
$te->setBaseDirectory(__DIR__);

$data = array(
    "name"    => "David",
    "surname" => "Gilmour",
    "genres"  => array("Progressive Rock", "Art Rock", "Blues Rock"),
    "albums"  => array("On an Island" => 2006, "Rattle That Lock" => 2015),
    "singles" => array(
        array("track" => "There's No Way Out of Here", "album" => "David Gilmour"),
        array("track" => "Blue Light", "album" => "About Face"),
        array("track" => "Love on the Air", "album" => "About Face")
    ),
    "date"    => function () {
        return date("Y/m/d");
    },
);

echo $te->render("singer.html", $data);

```

And the `singer.html` template file:

```

    My Favorite Singer

    {name} {surname}
    Genres

        {item}

    Albums

        {album} : {year}

    Singles

            {track} of the album {album}

    Today: {date}

```

### Scopes

[](#scopes)

Scopes override data with the same name of the higher level scope.

For example the `singer` records will overwrite `name` and `surname` in the following example:

```
use MiladRahimi\PHPTemplate\TemplateEngineFactory;

$te = TemplateEngineFactory::create();
$te->setBaseDirectory(__DIR__);

$data = array(
    "name" => "Selena",
    "surname" => "Gomez",
    "others" => array(
        array("name" => "Taylor", "surname" => "Swift"),
        array("name" => "Demi", "surname" => "Lovato")
    )
);

echo $te->render("singer.html", $data);

```

And the `singer.html` template file:

```

    Young Singers

    Young Singers
    Best Singer: {name} {surname}.
    Others:

        {name} {surname}

```

### Importing External Template Files

[](#importing-external-template-files)

You may need to import external files.

See the following example which `page.html` imports `head.html` file.

```
use MiladRahimi\PHPTemplate\TemplateEngineFactory;

$te = TemplateEngineFactory::create();
$te->setBaseDirectory(__DIR__);

$data = array(
    "page_title" => "Roger Waters Biography",
    "name"       => "Roger",
    "surname"    => "Waters",
);

echo $te->render("page.html", $data);

```

And the `page.html` template file:

```

    Welcome {name} {surname}!

```

And the `head.html` template file:

```

    {page_title}

```

### Framework Integration

[](#framework-integration)

You can install PHPTemplate using Composer. While all of modern PHP frameworks supports Composer packages, You can use PHPTemplate in the most of popular frameworks easily.

License
-------

[](#license)

PHPTemplate is created by [Milad Rahimi](http://miladrahimi.com)and released under the [MIT License](http://opensource.org/licenses/mit-license.php).

###  Health Score

27

—

LowBetter than 49% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity11

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity58

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

Unknown

Total

1

Last Release

3938d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/921274b8bb29236d8f94f6c83100a5f751f6394c4c49741e1b92bfbccac0911b?d=identicon)[miladrahimi](/maintainers/miladrahimi)

---

Top Contributors

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

---

Tags

templateviewtemplate engineengine

### Embed Badge

![Health badge](/badges/miladrahimi-phptemplate/health.svg)

```
[![Health](https://phpackages.com/badges/miladrahimi-phptemplate/health.svg)](https://phpackages.com/packages/miladrahimi-phptemplate)
```

###  Alternatives

[anourvalar/office

Generate documents from existing Excel &amp; Word templates | Export tables to Excel (Grids)

24085.2k](/packages/anourvalar-office)[leitsch/kirby-blade

Enable Laravel Blade Template Engine for Kirby 4 and Kirby 5

219.2k](/packages/leitsch-kirby-blade)

PHPackages © 2026

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