PHPackages                             webiny/htpl - 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. webiny/htpl

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

webiny/htpl
===========

PHP template engine based on html tags.

v0.1.0(10y ago)11233[6 issues](https://github.com/Webiny/Htpl/issues)MITPHPPHP &gt;=5.5.9

Since Jun 11Pushed 10y ago3 watchersCompare

[ Source](https://github.com/Webiny/Htpl)[ Packagist](https://packagist.org/packages/webiny/htpl)[ Docs](http://www.webiny.com/)[ RSS](/packages/webiny-htpl/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (1)Dependencies (2)Versions (3)Used By (0)

HTPL
====

[](#htpl)

HTPL is a PHP template engine that uses HTML5 tags. Here is a simple example:

```

            {k}: {v}

```

We wrote this template engine because we had a need for an engine that is light and extensible when it comes to file storage. For example, we want to be able to retrieve the source templates from a cloud storage and write compiled templates into memcache for faster execution. Another reason was that we wanted something that is very easy for designers to learn and to use.

Main features
-------------

[](#main-features)

1. It's secure, all values are automatically escaped before output
2. Supports layout inheritance
3. Easy to extend, no need to write any lexers
4. Very fast (in some cases it outperforms Smarty, Twig and Blade)
5. Simple and intuitive syntax

The Basics
==========

[](#the-basics)

The engine uses an instance of `TemplateProvider` to retrieve the source template, and it uses a `Cache` instance to store the compiled template for faster execution.

```
$provider = new \Webiny\Htpl\TemplateProviders\FilesystemProvider([__DIR__ . '/template']);
$cache = new \Webiny\Htpl\Cache\FilesystemCache(__DIR__ . '/temp/compiled');

$htpl = new \Webiny\Htpl\Htpl($provider, $cache);

$htpl->display('template.htpl');
```

There are a couple of built in template providers and cache providers. If you wish to build your own, just create a class and implement `\Webiny\Htpl\TemplateProviders\TemplateProviderInterface` for a template provider, or `\Webiny\Htpl\Cache\CacheInterface` for the cache.

See more:

- [Variables and modifiers](#variables-and-modifiers)
- [Functions](#functions)
- [Template inheritance](#template-inheritance)
- [License and Contributions](#license-and-contributions)
- [Resources](#resources)

Variables and modifiers
-----------------------

[](#variables-and-modifiers)

Variable values are printed using `{varName}` syntax. You can also attach different modifiers to variables, for example:

```
{someVar|lower|replace({"john":"doe", "bird":"fish:})}

```

The above code takes the value of `someVar`, makes it lowercase and replaces the word `john` with `doe`, and the word `bird` with `fish`.

As you can see, the modifiers are very easy to apply, and they can be chained together.

### Modifiers

[](#modifiers)

The following modifiers are built in:

#### numbers

[](#numbers)

- [Abs](#abs)
- [Round](#round)
- [Number format](#number-format)

#### strings

[](#strings)

- [Capitalize](#capitalize)
- [Lower](#lower)
- [Upper](#upper)
- [First upper](#first-upper)
- [Format](#format)
- [Length](#length)
- [Nl2br](#nl2br)
- [Raw](#raw)
- [Replace](#replace)
- [Strip tags](#strip-tags)
- [Trim](#trim)

#### array

[](#array)

- [First](#first)
- [Last](#last)
- [Join](#join)
- [Keys](#keys)
- [Values](#values)
- [Length](#length)
- [Json encode](#json-encode)

#### date / time

[](#date--time)

- [Date](#date)
- [Time ago](#time-ago)

#### other

[](#other)

- [Default](#default-value)

See also [building a custom modifier](#custom-modifiers).

#### Abs

[](#abs)

Absolute value

`someNum = -4`;

```
{someNum|abs} // 4

```

#### Round

[](#round)

Round the number.

`someNum = 3.555`;

```
{someNum|round} // 4
{someNum|round(2)} // 4.00
{someNum|round(2)} // 3.56
{someNum|round(2, "down")} // 3.549

```

The round modifier takes the `precision` point as the first parameter, and `mode` as the second parameter. The available `mode` values are: `up` or `down` and they define if the modifier should round up or round down.

#### Number format

[](#number-format)

Format the given number.

`num = 3500.1`

```
{num|numberFormat(2)} // 3,500.10
{num|numberFormat(3, ",", ".")} // 3.500,100

```

The modifier takes three parameters: `decimals`, `decimal point` and `thousands separator`.

#### Capitalize

[](#capitalize)

Capitalize the string.

`str = "some string"`

```
{str|capitalize} // Some String

```

#### Lower

[](#lower)

String to lowercase.

`str = "SOME STRING"`

```
{str|lower} // some string

```

#### Upper

[](#upper)

String to uppercase.

`str = "some string"`

```
{str|upper} // SOME STRING

```

#### First upper

[](#first-upper)

First letter to upper case.

`str = "some string"`

```
{str|firstUpper} // Some string

```

#### Format

[](#format)

Format a string by replacing the placeholders with given values.

`var = "My name is %s"`

```
{var|format({"John Snow"})} // My name is John Snow

```

The modifier takes an array of strings that should be replaced in the same order as the placeholders appear in the input string.

#### Length

[](#length)

Returns the string length or the number or elements inside an array.

`arr = ["one", "two", "three"]`

```
{arr|length} // 3

```

`str = "some string"`

```
{str|length} // 11

```

#### Nl2br

[](#nl2br)

Converts new lines to HTML's `br` tag.

`str = "Some\nString"`

```
{str|nl2br} // Some\nString

```

#### Raw

[](#raw)

Un-escapes the variable output.

`var = "string"`

```
{var} // &lt;div&gt;&lt;p&gt;string&lt;/p&gt;&lt;/div&gt;
{var|raw} // string

```

#### Replace

[](#replace)

Perform a find and replace on the given string.

`var = "John loves Khaleesi"`

```
{var|replace({"Khaleesi":"Tyrion"})} // John loves Tyrion

```

The modifier takes an array of key=&gt;value pairs defining what should be replaced.

#### Strip tags

[](#strip-tags)

Strips the HTML tags from the string.

`var = "Some HTML string"`

```
{var|stripTags} // Some HTML string
{var|stripTags("")} // Some HTML string

```

The modifier takes a comma separated list of allowed tags that shouldn't be replaced.

#### Trim

[](#trim)

Trims the given character from the beginning, end or from both sides of the string.

`str = "|Some string|"`

```
{str|trim("|")} // Some string
{str|trim("|", "left")} // Some string|
{str|trim("|", "right")} // |Some string

```

The modifier takes the char that should be trimmed as the first parameter, and the trim direction as the second parameter.

#### First

[](#first)

Return the first value from the array.

`arr = ["one", "two", "three"]`

```
{arr|first} // one

```

#### Last

[](#last)

Return the last value from the array.

`arr = ["one", "two", "three"]`

```
{arr|last} // three

```

#### Join

[](#join)

Join the array pieces with the given glue.

`arr = ["one", "two", "three"]`

```
{arr|join(",")} // one,two,three

```

The modifier takes the glue as the parameter.

#### Keys

[](#keys)

Return the array keys.

`arr = ["keyOne"=>"one", "keyTwo"=>"two", "keyThree"=>"three"]`

```
{arr|keys} // ["keyOne", "keyTwo", "keyThree"]

```

#### Values

[](#values)

Return the array values.

`arr = ["keyOne"=>"one", "keyTwo"=>"two", "keyThree"=>"three"]`

```
{arr|values} // ["one", "two", "three"]

```

#### Json encode

[](#json-encode)

Json encode the given array.

`arr = ["one", "two", "three"]`

```
{arr|jsonEncode} // {"one", "two", "three"}

```

#### Date

[](#date)

Display the date.

`date = "2015-01-01 14:25"`

```
{date|date("F j, Y, g:i a")} // January 1, 2015, 2:25 pm

```

The `date` modifier uses PHP date internally, meaning you can pass any PHP date format and it will parse it.

#### Time ago

[](#time-ago)

This is a helper modifier for displaying the date/time in a `time ago` format.

`date = "2015-01-01 14:25"`

```
{date|timeAgo} // 4 months ago

```

#### Default value

[](#default-value)

Return a default value if the variable is empty.

`var` is not defined.

```
{var|default("some value")} // some value

```

#### Custom modifiers

[](#custom-modifiers)

To add a custom modifier, create a class that implements `\Webiny\Htpl\Modifiers\ModifierPackInterface` and assign the class instance to your Htpl instance:

```
$myModifierPack = new MockModifierPack();
$htpl->registerModifierPack($myModifierPack);
```

It's worth checking out the built-in [CorePack](src/Webiny/Htpl/Modifiers/CorePack.php) to get a sense of the implementation.

Functions
---------

[](#functions)

The template engine provides just a few core functions that are sufficient in about 95% of your needs. For the remaining 5%, HTPL provides a simple way to integrate any custom function.

Lets take a look at what is supported.

### If, Else, ElseIf

[](#if-else-elseif)

The `if` function, and its siblings `else` and `elseif`, provide a way for executing/showing a particular part of the template, based on whether or not the logical condition is met.

```

    the value of someVar equals to someString

    someVar is larger than 100

    something else - in case both upper conditions are false

```

### Include a template

[](#include-a-template)

An external template can be included using the `w-include` tag.

```

```

If the value of the `file` attribute doesn't have an `.htpl` extension, it will be read as a variable, and the engine will try to retrieve the template name from the variable and include it. **Note:** Only `.htpl` files can be included. The `.htpl` files cannot contain any PHP code.

```

```

### Loops

[](#loops)

The loop parameter takes the `items` attribute, which is the object you wish to loop through, and the `var` attribute, which marks the current object value inside the loop. Also an optional attribute `key` can be passed, that holds the object's key value.

```

    {k}: {v}

```

### Literal

[](#literal)

The `w-literal` tag marks the content that should not be parsed. This is useful when you are using curly braces `{}` inside your JavaScript code, so that the template engine doesn't raise an error.

```

        var object = {"name":"john"};

```

### Minify

[](#minify)

This is a handy function that minifies and concatenates all marked JavaScript or CSS files into one file and strips out comments and new lines, making the file much faster to download.

A sample template like this:

```

```

Would output something like this:

```

```

The script automatically tracks when the file was changed and creates a new minified file, with a different name, so it's automatically refreshed in the user's browser. **Note:** Don't place js and css files together inside the same `w-minify` block.

#### Configuring minify

[](#configuring-minify)

The minify function needs to be configured before it can be used.

```
// get your Htpl instance
$htpl = new \Webiny\Htpl\Htpl($provider, $cache);

// define the minify options
$htpl->setOptions([
    'minify' => [
        'driver'    => 'Webiny\Htpl\Functions\WMinify\WMinify',
        'provider'  => $providerInstance,
        'cache'     => $cacheInstance,
        'webRoot'   => '/minified/'
    ]
]);
```

The `driver` parameter is an optional parameter. If not defined, it will use the internal minification class. In case you wish to use some other minification class, you can create your own driver by extending `\Webiny\Htpl\Functions\WMinify\WMinifyAbstract`.

The `provider` parameter is an instance of a template provider, which can be a different instance from the one used for the Htpl instance. This `provider` tells the minifier where to look for source files.

The `cache` parameter is an instance of a cache, which can also be a different instance than the one used for Htpl instance. The `cache` tells the minifier where to save the minified files.

When a minified file is created, it will be stored somewhere by the cache provider. In order to point to that directory using a web URL, the minify component needs to know the web absolute path to that location. That path is set inside the `webRoot` option.

Template inheritance
--------------------

[](#template-inheritance)

Template inheritance is done using layouts and blocks.

For example:

`layout.htpl` content:

```

```

`template.htpl` content:

```

    Hello World

        This is my content

```

The output:

```

    Hello World

    This is my content

```

**Note**: inside the `w-layout` tag, all content that is not inside a `w-block` tag will get dropped.

License and Contributions
-------------------------

[](#license-and-contributions)

Contributing &gt; Feel free to send PRs.

License &gt; [MIT](LICENSE)

Resources
---------

[](#resources)

To run unit tests, you need to use the following command:

```
$ cd path/to/Htpl/
$ composer install
$ phpunit

```

###  Health Score

24

—

LowBetter than 32% of packages

Maintenance9

Infrequent updates — may be unmaintained

Popularity15

Limited adoption so far

Community14

Small or concentrated contributor base

Maturity49

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 95% 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 ~0 days

Total

2

Last Release

3994d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/4c1fbd2989c3dc9eba2c45f72fe4727d5cf1bde9ef6ff014c2b961e95636a6dc?d=identicon)[swader](/maintainers/swader)

![](https://www.gravatar.com/avatar/4440afa738ed146b05c06073a90345e0464c4f4d042b039532d881ca24859d77?d=identicon)[SvenAlHamad](/maintainers/SvenAlHamad)

---

Top Contributors

[![SvenAlHamad](https://avatars.githubusercontent.com/u/3808420?v=4)](https://github.com/SvenAlHamad "SvenAlHamad (19 commits)")[![Swader](https://avatars.githubusercontent.com/u/1430603?v=4)](https://github.com/Swader "Swader (1 commits)")

---

Tags

template engine

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/webiny-htpl/health.svg)

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

###  Alternatives

[phptal/phptal

PHPTAL is a templating engine for PHP5 that implements Zope Page Templates syntax

179421.6k19](/packages/phptal-phptal)[foil/foil

PHP template engine for native PHP templates

170111.2k7](/packages/foil-foil)[proai/laravel-handlebars

A Laravel wrapper for LightnCandy for using the Handlebars (and Mustache) template engine.

38204.7k](/packages/proai-laravel-handlebars)[talesoft/tale-pug

A clean, lightweight and easy-to-use templating engine for PHP based on Pug, formerly Jade

319.4k3](/packages/talesoft-tale-pug)[wanze/template-engine-factory

Provides ProcessWire integration for various template engines such as Twig.

2612.0k4](/packages/wanze-template-engine-factory)[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)
