PHPackages                             larsgmortensen/liteview - 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. larsgmortensen/liteview

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

larsgmortensen/liteview
=======================

Lightweight PHP template engine with compile-time inheritance and dependency-aware caching.

v1.0.2(7mo ago)0201GPL-3.0-or-laterPHPPHP &gt;=8.1

Since Sep 10Pushed 7mo ago1 watchersCompare

[ Source](https://github.com/LarsGMortensen/LiteView)[ Packagist](https://packagist.org/packages/larsgmortensen/liteview)[ Docs](https://github.com/LarsGMortensen/LiteView)[ RSS](/packages/larsgmortensen-liteview/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (1)DependenciesVersions (4)Used By (1)

LiteView - A Lightweight &amp; High-Performance PHP Template Engine
===================================================================

[](#liteview---a-lightweight--high-performance-php-template-engine)

LiteView is a **fast, minimal, efficient, single-file PHP template engine** focused on **runtime performance** and **developer ergonomics**. It offers a very **low overhead** and an intuitive syntax inspired by other modern template engines while staying dependency-free and easy to embed in any codebase (**PHP 8.1+**).

---

🚀 Features that make LiteView stand out
---------------------------------------

[](#-features-that-make-liteview-stand-out)

- **Blazing-fast compilation** – Templates are turned into pure, optimized PHP with near-zero overhead.
- **Smart caching** – Dependency-aware cache with atomic writes and OPcache refresh ensures instant, safe performance boosts.
- **Elegant inheritance and includes** – {% extends %}, {% block %}, {% yield %} and {% include %} for clean, DRY layouts – with strict fail-fast validation to catch mistakes early.
- **Modern syntax** – Write templates using {% if %}, {% foreach %}, {{ variable }}, {{{ raw }}}, and {?= expr ?} – simple, powerful, familiar.
- **Conditionals &amp; Loops** – Native `{% if %}`, `{% foreach %}`, and `{% endif %}` syntax.
- **Safe Output** – Escaping with `{{ variable }}` to prevent XSS attacks.
- **Secure by default** – Automatic HTML-escaping prevents XSS, while trusted raw output is still available when needed.
- **Lightweight by design** – Single file, zero dependencies, fully static API. Perfect for performance-critical apps.
- **Configurable flexibility** – Toggle whitespace trimming, HTML comment removal, and PHP block support.
- **Production-ready** – Strict error handling, safe path resolution, and reliable cache invalidation built-in.
- **Minimal Overhead** – Designed for maximum performance with no dependencies.
- **Static API** – Fully static, no instantiation required.
- **Developer friendly** – No bootstrapping, no learning curve – just drop in and start rendering.

---

📦 Installation
--------------

[](#-installation)

Via Composer (recommended):

```
composer require larsgmortensen/liteview
```

Or manually add the class file (e.g. `src/LiteView/LiteView.php`) and load it via Composer’s autoloader or a `require_once`:

```
use LiteView\LiteView;
require_once __DIR__.'/src/LiteView/LiteView.php';
```

> **Tip:** Place your **cache directory outside webroot** (or deny direct access).

---

🚀 Quick Start
-------------

[](#-quick-start)

```
use LiteView\LiteView;

LiteView::render(
    'home.html',                  // Template file (relative to $templatePath)
    '/path/to/templates/',        // Template directory
    true,                         // Enable cache
    '/path/to/cache/',            // Cache directory
    true,                         // Trim whitespace
    true,                         // Remove HTML comments
    ['title' => 'Hello World'],   // Data/template variables
    true                          // Allow raw PHP blocks ({? ... ?})
);
```

Capture output as a string:

```
$html = LiteView::renderToString(
    'page.html',
    '/path/to/templates/',
    true,
    '/path/to/cache/',
    false,
    false,
    ['user' => $user],
    false // disallow raw PHP tags
);
```

### Layout (`layout.html`)

[](#layout-layouthtml)

```

  {% yield title %}

  {% include "partials/header.html" %}

    {% yield content %}

```

### Page template (`index.html`)

[](#page-template-indexhtml)

```
{% extends "layout.html" %}

{% block title %}{{ $meta_title }}{% endblock %}

{% block content %}
    Home
    Welcome to the home page, list of colors:

    {% if (isset($something) || isset($something["else"])) %}
        Do something
    {% endif %}

        {% foreach ($colors as $color) %}
        {{ $color }}
        {% endforeach %}

{% endblock %}
```

---

🔤 Template Syntax
-----------------

[](#-template-syntax)

FeatureSyntaxNotes**Escaped output**`{{ expr }}`Encoded with `htmlspecialchars(..., ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8')`.**Raw output**`{{{ expr }}}`No escaping. Only for **trusted** HTML.**Raw PHP echo**`{?= expr ?}`Emits the evaluated expression directly.**Raw PHP block**`{? /* php */ ?}`Executes only if `allowPhpTags=true`.**If / Elseif / Else / Endif**`{% if (...) %}...{% elseif (...) %}{% else %}{% endif %}`Pure PHP conditions.**Foreach / Endforeach**`{% foreach ($items as $i) %}...{% endforeach %}`Pure PHP foreach.**Extends**`{% extends "layout.html" %}`One parent per template.**Block / Endblock**`{% block name %}...{% endblock %}`Defines content for a named yield.**Yield**`{% yield name %}`Replaced with the child’s matching block.**Include**`{% include "file.html" %}`Recurses with depth guard (16).**Template comments**`{# ... #}`**Nested** comments supported. Removed before parsing.> **Quotes:** Always use **double quotes** in `{% extends %}` and `{% include %}`.

---

📖 User Guide
------------

[](#-user-guide)

LiteView is designed to be **simple, fast, and intuitive**. Below you’ll find examples of all supported features so you can get productive immediately.

---

### 🔒 Secure Output

[](#-secure-output)

Escape variables safely with `{{ ... }}`:

```
{{ $username }}
```

This prevents XSS by applying `htmlspecialchars()`.

For raw output (no escaping), use triple braces:

```
{{{ $trustedHtml }}}
```

⚠ Only use raw output with trusted content.

---

### 📂 Template Inheritance

[](#-template-inheritance)

Define reusable layouts with `{% extends %}`, `{% block %}`, and `{% yield %}`.

#### layout.html

[](#layouthtml)

```

    {% yield title %}

    {% yield header %}
    {% yield content %}

```

#### index.html

[](#indexhtml)

```
{% extends "layout.html" %}

{% block title %}Home{% endblock %}

{% block header %}Welcome{% endblock %}

{% block content %}
    Welcome to the home page, list of colors:
    {% if (isset($something) || isset($something["else"])) %}
        Do something
    {% endif %}

        {% foreach ($colors as $color) %}
        {{ $color }}
        {% endforeach %}

{% endblock %}
```

LiteView enforces **strict fail-fast validation**:

- Child blocks must match parent yields.
- Duplicate or missing blocks will throw exceptions at compile-time.

---

### 📦 Includes

[](#-includes)

Insert reusable snippets with `{% include "..." %}`:

```
{% include "partials/footer.html" %}
```

Includes are recursive and protected against infinite loops with a depth guard.

---

### ❌ Comments

[](#-comments)

Comment out code with `{# ... #}`:

```
{# This is a comment and will be removed #}
```

Supports **nested comments** safely.

---

### ➡️ Nested comments

[](#️-nested-comments)

LiteView supports **nested `{# ... #}` comments**, something most template engines do not.

This means you can safely comment out larger blocks of code without worrying about inner `{# ... #}` markers breaking the parser:

```
{# Outer comment start

      {# Inner comment #}
      Content hidden

#}
```

The entire block is removed cleanly, leaving no stray `#}` in the output.

---

### 🔀 Conditionals

[](#-conditionals)

Use native PHP expressions:

```
{% if ($user == "admin") %}
    Admin Panel
{% else %}
    User Panel
{% endif %}
```

---

### 🔁 Loops

[](#-loops)

Iterate with `foreach`:

```

    {% foreach ($items as $item) %}
        {{ $item }}
    {% endforeach %}

```

---

### ✂ Whitespace Trimming

[](#-whitespace-trimming)

If enabled, LiteView removes redundant whitespace outside ``, ``, ``, ``, and ``:

```
    Hello     World
```

➡ becomes:

```
Hello World
```

---

### 🗑 HTML Comment Removal

[](#-html-comment-removal)

If enabled, HTML comments are removed (except conditional IE comments):

```

Hello
```

➡ becomes:

```
Hello
```

---

### 🐘 Embedding PHP

[](#-embedding-php)

Raw PHP blocks are allowed (configurable via `$allowPhpTags`):

```
{? echo strtoupper("hello world"); ?}
```

If disabled, these tags are ignored.

---

### 🔥 Clearing the Cache

[](#-clearing-the-cache)

Force templates to recompile by clearing the cache:

```
LiteView::clearCache();
```

Deletes all compiled `.php` templates in the cache directory.

---

🧰 API
-----

[](#-api)

```
LiteView::render(
    string $template,
    string $templatePath,
    bool   $cacheEnabled,
    string $cachePath,
    bool   $trimWhitespace = false,
    bool   $removeHtmlComments = false,
    array  $data = [],
    bool   $allowPhpTags = true
): void

LiteView::renderToString(...): string

LiteView::clearCache(): void
```

**Parameters**

- **$templatePath**: Template root (must resolve via `realpath` under this root).
- **$cachePath**: Directory for compiled templates. Must be writable.
- **$allowPhpTags**: If `false`, `{? ... ?}` blocks are stripped (safe mode). `{?= ... ?}` remains a direct echo transform.
- **$trimWhitespace**: Collapses runs of whitespace **outside** sensitive tags: ``, ``, ``, ``, ``.
- **$removeHtmlComments**: Removes standard HTML comments while preserving IE conditional comments.

---

💡 Why LiteView?
---------------

[](#-why-liteview)

LiteView exists for developers who want **performance and simplicity** without the overhead of large engines like Twig or Smarty.

✨ **Blazing Fast** – Compiles to lean PHP with minimal overhead.

✨ **Fail-Fast Safety** – Strict inheritance validation prevents silent template bugs.

✨ **Zero Dependencies** – Pure PHP, fully static API, no instantiation.

✨ **Full PHP Power** – Use real PHP expressions in conditionals and loops.

✨ **Lightweight by Design** – Single-file engine, ideal for micro-frameworks and high-traffic apps.

✨ **Flexible &amp; Configurable** – Toggle whitespace trimming, HTML comment removal, and raw PHP execution.

LiteView is the perfect balance of **developer productivity** and **runtime performance**. 🚀

---

🧬 Strict Inheritance (Fail-Fast)
--------------------------------

[](#-strict-inheritance-fail-fast)

LiteView resolves blocks **at compile time** and enforces invariants:

- **Missing yield:** If a child defines `{% block name %}` that the parent doesn’t yield, **compilation fails**.
- **Missing block:** If the parent contains `{% yield name %}` that the child doesn’t define, **compilation fails**.
- **Duplicate block:** If the child defines the same block twice, **compilation fails**.

This catches layout mistakes early and keeps runtime hot paths minimal (no runtime block stack).

---

🗜️ Caching &amp; Invalidation
-----------------------------

[](#️-caching--invalidation)

- Compiled PHP is written to the cache directory using **atomic rename**.
- Invalidation compares the cache mtime against the **max mtime** of the source template and **all discovered dependencies** (`extends` + recursive `include`).
- On successful write, LiteView calls `opcache_invalidate($file, true)` when available and clears PHP’s stat cache for the file.

**Deploy note:** If your deployment preserves file mtimes (`cp -p`, `rsync --times`), changes might not trigger recompilation. Ensure mtimes update or call `LiteView::clearCache()` post-deploy.

---

🔐 Security Notes
----------------

[](#-security-notes)

- Templates are considered **trusted code**. Avoid granting authoring access to untrusted users.
- `{? code ?}` executes raw PHP. You can disable it by setting `$allowPhpTags = false`.
- `{?= expr ?}` (expression output) **always works** and cannot be disabled.
- Variable output is HTML-escaped by default (`{{ variable }}`). Use `{{{ ... }}}` only with trusted HTML.
- Always place `cachePath` **outside webroot**, or restrict access (e.g., with `.htaccess`).

---

🧪 Troubleshooting
-----------------

[](#-troubleshooting)

- **"illegal template path"** -&gt; The resolved file is outside the template root; check relative paths and root.
- **"duplicate block" / "not yielded" / "missing child blocks"** -&gt; Inheritance contract violated. Align parent yields and child blocks.
- **No recompilation after deploy** -&gt; Ensure mtimes change or run `clearCache()`.
- **Windows rename failure** -&gt; LiteView unlinks the destination and retries automatically.

---

📈 Performance Tips
------------------

[](#-performance-tips)

- Enable caching in production.
- Keep templates lean and modular – heavy logic belongs in PHP, not templates.
- Place cache outside webroot (or protect with `.htaccess`).
- OPcache integration is automatic – LiteView invalidates cached PHP files as needed.
- Avoid excessive includes – each include adds a dependency check.
- Enable whitespace trimming and HTML comment removal for production builds.
- Disable `$allowPhpTags` in production unless you explicitly need raw `{? ... ?}` blocks.

---

📦 Packagist
-----------

[](#-packagist)

LiteView on Packagist: 👉

---

📜 License
---------

[](#-license)

LiteView is released under the **GNU General Public License v3.0**. See [LICENSE](LICENSE) for details.

🤝 Contributing
--------------

[](#-contributing)

Contributions are welcome! Feel free to fork this repository, submit issues, or open a pull request.

✍️ Author
---------

[](#️-author)

Developed by **Lars Grove Mortensen** © 2025. Feel free to reach out or contribute!

---

LiteView – the single-file engine that gives you speed, safety, and simplicity 🚀

---

🌟 **If you find this library useful, give it a star on GitHub!** 🌟

###  Health Score

33

—

LowBetter than 75% of packages

Maintenance63

Regular maintenance activity

Popularity7

Limited adoption so far

Community11

Small or concentrated contributor base

Maturity46

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

Total

3

Last Release

234d ago

PHP version history (2 changes)v1.0.1PHP ^8.1

v1.0.2PHP &gt;=8.1

### Community

Maintainers

![](https://www.gravatar.com/avatar/e00ea2f83af8b74d6813e4a7e97f3095308fd56d1047f3a791b50f699798c5ca?d=identicon)[LarsGMortensen](/maintainers/LarsGMortensen)

---

Top Contributors

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

---

Tags

phpcachingtemplatetemplatingviewlightweightengineinheritance

### Embed Badge

![Health badge](/badges/larsgmortensen-liteview/health.svg)

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

###  Alternatives

[eftec/bladeone

The standalone version Blade Template Engine from Laravel in a single php file

8208.4M87](/packages/eftec-bladeone)[eftec/bladeonehtml

The standalone version Blade Template Engine from Laravel in a single php file

1018.1k5](/packages/eftec-bladeonehtml)

PHPackages © 2026

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