PHPackages                             nitricware/tonic - 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. nitricware/tonic

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

nitricware/tonic
================

PHP template engine without dependencies.

3.3.1(5y ago)022BSD-3-ClausePHPPHP &gt;=7.4

Since Jul 16Pushed 5y ago1 watchersCompare

[ Source](https://github.com/nitricware/tonic)[ Packagist](https://packagist.org/packages/nitricware/tonic)[ Docs](https://github.com/nitricware/tonic)[ RSS](/packages/nitricware-tonic/feed)WikiDiscussions master Synced 1w ago

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

tonic
=====

[](#tonic)

Super fast and powerful template engine. Pure PHP, zero dependencies.

This fork of tonic continues the work of rgamba.

Usage
-----

[](#usage)

Using Tonic is pretty straight forward.

```
use Tonic\Tonic;
$tpl = new Tonic("demo.html");
$tpl->user_role = "member";
echo $tpl->render();
```

It's also very flexible. The above code can also be written like:

```
$tpl = new Tonic();
echo $tpl->load("demo.html")->assign("user_role","member")->render();
```

Show me the syntax
------------------

[](#show-me-the-syntax)

Using Tonic

```

Welcome {$user.name.capitalize().truncate(50)}
User role: {$role.lower().if("admin","administrator").capitalize()}

```

vs. writing all in PHP

```

Welcome  50 ? substr(ucwords($user["name"]),0,50)."..." : ucwords($user["name"])) ?>
User role:

```

Installation
------------

[](#installation)

Install using composer

```
{
    "require": {
        "nitricware/tonic": "^3.0"
    }
}
```

Caching
-------

[](#caching)

All tonic templates are compiled back to native PHP code. It's highly recommended that you use the caching functionality so that the same template doesn't need to be compiled over and over again increasing the CPU usage on server side.

```
$tpl = new Tonic();
$tpl->cache_dir = "./cache/"; // Be sure this directory exists and has writing permissions
$tpl->enable_content_cache = true; // Importante to set this to true!
```

Modifiers
---------

[](#modifiers)

Modifiers are functions that modify the output variable in various ways. All modifiers must be preceded by a variable and can be chained with other modifiers. Example:

```
{$variable.modifier1().modifier2().modifier3()}
```

We can also use modifiers in the same way when using associative arrays:

```
{$my_array.item.sub_item.modifier1().modifier2().modifier3()}
```

Working with dates
------------------

[](#working-with-dates)

It's easy to handle and format dates inside a Tonic template.

```
Tonic::$local_tz = 'America/New_york'; // Optionaly set the user's local tz
$tpl = new Tonic();
$tpl->my_date = date_create();
```

And the template

```
Today is {$my_date.date("Y-m-d h:i a")}
```

Working with timezones

```
The local date is {$my_date.toLocal().date("Y-m-d h:i a")}
```

Which will render `$my_date` to the timezone configured in ` Tonic::$local_tz`

### Custom timezone

[](#custom-timezone)

```
The local date is {$my_date.toTz("America/Mexico_city").date("Y-m-d h:i a")}
```

### List of modifiers

[](#list-of-modifiers)

NameDescription`upper()`Uppercase`lower()`Lowercase`capitalize()`Capitalize words (ucwords)`abs()`Absolute value`truncate(len)`Truncate and add "..." if string is larger than "len"`count()`Alias to count()`length()`alias to count()`date(format)`Format date like date(format)`nl2br()`Alias to nl2br`stripSlashes()`Alias to stripSlashes()`sum(value)`Sums value to the current variable`substract(value)`Substracts value to the current variable`multiply(value)`Multiply values`divide(value)`Divide values`addSlashes()`Alias of addSlashes()`encodeTags()`Encode the htmls tags inside the variable`decodeTags()`Decode the tags inside the variable`stripTags()`Alias of strip\_tags()`urldecode()`Alias of urldecode()`trim()`Alias of trim()`sha1()`Returns the sha1() of the variable`numberFormat(decimals)`Alias of number\_format()`lastIndex()`Returns the last array's index of the variable`lastValue()`Returns the array's last element`jsonEncode()`Alias of json\_encode()`replace(find,replace)`Alias of str\_replace()`default(value)`In case variable is empty, assign it value`ifEmpty(value [,else_value])`If variable is empty assign it value, else if else\_value is set, set it to else\_value`if(value, then_value [,else_value [,comparisson_operator]] )`Conditionally set the variable's value. All arguments can be variables`preventTagEncode()`If ESCAPE\_TAGS\_IN\_VARS = true, this prevents the variable's value to be encoded### Creating custom modifiers

[](#creating-custom-modifiers)

If you need a custom modifier you can extend the list and create your own.

```
// This function will only prepend and append some text to the variable
Tonic::extendModifier("myFunction",function($input, $prepend, $append = ""){
    // $input will hold the current variable value, it's mandatory that your lambda
    // function has an input receiver, all other arguments are optional
    // We can perform input validations
    if(empty($prepend)) {
        throw new \Exception("prepend is required");
    }
    return $prepend . $input . $append;
});
```

And you can easily use this modifier:

```
{$name.myFunction("hello "," goodbye")}
```

### Anonymous modifiers

[](#anonymous-modifiers)

Sometimes you just need to call functions directly from inside the template whose return value is constantly changing and therefore it can't be linked to a static variable. Also, it's value is not dependant on any variable. In those cases you can use anonymous modifiers. To do that, you need to create a custom modifier, IGNORE the `$input` parameter in case you need to use other parameters.

```
Tonic::extendModifier("imagesDir", function($input){
    // Note that $input will always be empty when called this modifier anonymously
    return "/var/www/" . $_SESSION["theme"] . "/images";
});
```

Then you can call it directly from the template

```

```

Context awareness
-----------------

[](#context-awareness)

Tonic prevents you from escaping variables in your app that could led to possible attacks. Each variable that's going to be displayed to the user should be carefully escaped, and it sould be done acoardingly to it's context. For example, a variable in a href attr of a link should be escaped in a different way from some variable in a javascript tag or a `` tag. The good news is that tonic does all this work for you.

```
$tonic->assign("array",array("Name" => "Ricardo", "LastName", "Gamba"));
$tonic->assign("ilegal_js","javascript: alert('Hello');");
```

And the HTML

```
Click me

The ilegal js is: {$ilegal_js}

Valid link generated

 We can also ignore the context awareness: {$ilegal_js.ignoreContext()}
```

Include templates
-----------------

[](#include-templates)

You can include a template inside another template

```
{include footer.html}
```

We can also fetch and external page and load it into our current template

```
{include http://mypage.com/static.html}
```

Templates includes support nested calls, but beware that infinite loop can happen in including a template "A" inside "A" template.

Control structures
------------------

[](#control-structures)

### If / else

[](#if--else)

Making conditionals is very easy

```
{if $user.role eq "admin"}
Hello admin
{elseif $user.role.upper() eq "MEMBER" or $user.role.upper() eq "CLIENT"}
Hello member
{else}
Hello guest
{endif}
```

You can use regular logic operators (==, !=, &gt;, &lt;, &gt;=, &lt;=, ||, &amp;&amp;) or you can use the following

OperatorEquivalenteq==neq!=gt&gt;lt&lt;gte&gt;=lte&lt;=### Loops

[](#loops)

```

{loop $user in $users}
{$user.name.capitalize()}
{endloop}

```

Or if the array key is needed

```

{loop $i,$user in $users}
{$i} - {$user.name.capitalize()}
{endloop}

```

### Working with macros

[](#working-with-macros)

Both if structures and loop constructs can be written in a more HTML-friendly way so your code can be more readable. Here's an example:

```

    Hello {$user}

```

Which is exactly the same as:

```
{if $users}

    {loop $user in $users}
    Hello {$user}
    {endloop}

{endif}
```

Localizing
----------

[](#localizing)

Tonic has localization support. Alter the calling as followed:

```
use Tonic\Tonic;
$tpl = new Tonic("demo.html", "localized.xml");
$tpl->user_role = "member";
echo $tpl->render();
```

If you want to use multiple localization files, use an array as the second construct parameter like so:

```
$tpl = new Tonic("demo.html", array("localized.xml", "anotherFile.xml");
```

The file `localized.xml` can have any name (i.e. `EN.xml`) but must be valid XML. Here’s its structure:

```

		TEXT
		Tonic will automatically load the specified localized text from the specified language file.

```

To access a localized string in you template use `{$localized.FILENAME.KEY}` while `KEY` is the key you used in the XML-Document and `FILENAME`is the name of the localization file without the extension (i.e. `EN`). In this example that would be `{$localized.EN.TEXT}`.

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

[](#template-inheritance)

Tonic supports single template inheritance. The idea behind this is to keep things nice and simple. Multiple inheritance can lead to complicated views difficult to maintain.

In Tonic, template inheritance is based on `blocks`. Suppose we have the following base template:

**base.html**

```

Tonic

    Default welcome message!

        This is the default content.

Tonic 2016

```

Then you have several partial templates or views and you would like to reuse the main `base.html` as a "skeleton". To do that, we work with `blocks`. Each block is defined by the tag `{block name}{endblock}` and/or by the html attribute `tn-block="name"` which effectively encloses the HTML element with the attibute as the block with the name **name**.

**inner.html**

```
{ extends base.html }

    Welcome to my inner page!

This content WON´T be rendered at all!

    This is the content of my inner view.

```

As a result we will have the following view:

```

Tonic

    Welcome to my inner page!

        This is the content of my inner view.

Tonic 2016

```

There are several keys here:

- The `{ extend }` tag. Which first and only argument should be the template file relative to `Tonic::$root` (by default `./`).
- The `tn-block="header"` html attribute that defines the block and is enclosed by the closing matching tag of the HTML element.
- All the blocks found in the child template (inner.html) will effectively replace the matching blocks on the parent template (base.html). If there is a block in the child template that is not defined in the parent template, **that block won´t be rendered at all**.
- Block names must only by alphanumerical with and must not contain `$` or any special characters or spaces.
- The parent template (base.html) inherits the context (scope, variables) of the child template.
- You can only extend 1 template.

**NOTE** It is also possible to define blocks using the `{block header}{endblock}` notation. We prefer to use HTML attributes as it is cleaner. Example:

```
{block myBlock}Welcome{endblock}
```

is exactly the same as:

```
Welcome
```

Roadmap
-------

[](#roadmap)

- add more `@throws` instead of `@return bool|void`.

Changelog
---------

[](#changelog)

- 16-07-2020 - 3.3.1 - composer fixes
- 14-07-2020 - 3.3 - PHP 7.4 Update: added type hinting and removed unused functionality
- 10-05-2019 - 3.2 - NitricWare Fork: Localization Support
- 11-10-2016 - 3.1.0 - Added support for template inheritance
- 25-03-2015 - 3.0.0 - Added Context Awareness and Maco Syntax for ifs and loops
- 23-03-2015 - 2.2.0 - Added namespace support and added modifier exceptions
- 20-03-2015 - 2.1.0 - Added the option to extend modifiers.
- 19-03-2015 - 2.0.0 - IMPORTANT update. The syntax of most structures has changed slightly, it's not backwards compatible with previous versions.

###  Health Score

25

—

LowBetter than 37% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity6

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity55

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 71.8% 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

2132d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/0de3ce105b67096aa4cf6ae39d1e4f6f371541174b264fedc4191a90aa4c5e21?d=identicon)[nitricware](/maintainers/nitricware)

---

Top Contributors

[![rgamba](https://avatars.githubusercontent.com/u/3084582?v=4)](https://github.com/rgamba "rgamba (56 commits)")[![nitricware](https://avatars.githubusercontent.com/u/10908453?v=4)](https://github.com/nitricware "nitricware (22 commits)")

---

Tags

phphtmltemplate

### Embed Badge

![Health badge](/badges/nitricware-tonic/health.svg)

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

###  Alternatives

[phug/phug

Pug (ex-Jade) facade engine for PHP, HTML template engine structured by indentation

67292.2k13](/packages/phug-phug)

PHPackages © 2026

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