PHPackages                             codewithkyrian/jinja-php - 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. codewithkyrian/jinja-php

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

codewithkyrian/jinja-php
========================

A minimalistic PHP implementation of the Jinja templating engine, specifically designed for parsing and rendering ML chat templates.

2.1.0(6mo ago)13236.7k↓11%2[1 issues](https://github.com/CodeWithKyrian/jinja-php/issues)2MITPHPPHP ^8.1CI passing

Since Mar 19Pushed 6mo ago1 watchersCompare

[ Source](https://github.com/CodeWithKyrian/jinja-php)[ Packagist](https://packagist.org/packages/codewithkyrian/jinja-php)[ RSS](/packages/codewithkyrian-jinja-php/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (3)Dependencies (4)Versions (4)Used By (2)

Jinja PHP
=========

[](#jinja-php)

[![Build Status](https://github.com/CodeWithKyrian/jinja-php/actions/workflows/test.yml/badge.svg?branch=main)](https://github.com/CodeWithKyrian/jinja-php/actions/workflows/test.yml)[![GitHub source](https://camo.githubusercontent.com/88e61eb211719144efdd570290a0456b6e13099c2df8d973f1bb43fe33bf0039/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4769746875622d736f757263652d696e666f726d6174696f6e616c3f6c6f676f3d676974687562)](https://github.com/CodeWithKyrian/jinja-php/)[![GitHub license](https://camo.githubusercontent.com/7ba7c5ce1a2d33d015049e5f807bd7caf5b4e3f0733ab700ed03515c418d2e88/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f436f6465576974684b797269616e2f6a696e6a612d7068702e737667)](https://github.com/codewithkyrian/jinja-php/blob/main/LICENSE)[![GitHub release](https://camo.githubusercontent.com/ce2fd69825587e416bf16e899a6b725364f8af0e802b759070cd62daf26a06ed/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f72656c656173652f436f6465576974684b797269616e2f6a696e6a612d7068702e737667)](https://github.com/byjg/php-jinja/releases/)

A **zero-dependency** PHP implementation of the Jinja templating engine, specifically designed for parsing and rendering machine learning (ML) chat templates. This project is heavily inspired by HuggingFace's Jinja template engine in JavaScript, intended primarily for ML chat templates, but is versatile enough to be used for general purposes of parsing most Jinja templates.

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

[](#installation)

Install Jinja PHP through Composer:

```
composer require codewithkyrian/jinja-php
```

Quick Start
-----------

[](#quick-start)

Here's how you can use Jinja PHP to render a template:

```
$sourceString = "{{ bos_token }}{% for message in messages %}{% if (message['role'] == 'user') != (loop.index0 % 2 == 0) %}{{ raise_exception('Conversation roles must alternate user/assistant/user/assistant/...') }}{% endif %}{% if message['role'] == 'user' %}{{ '[INST] ' + message['content'] + ' [/INST]' }}{% elif message['role'] == 'assistant' %}{{ message['content'] + eos_token + ' ' }}{% else %}{{ raise_exception('Only user and assistant roles are supported!') }}{% endif %}{% endfor %}";
$args = [
    'messages' => [
        ['role' => 'user', 'content' => 'Hello!'],
        ['role' => 'assistant', 'content' => 'Hi! How are you?'],
        ['role' => 'user', 'content' => 'I am doing great.'],
        ['role' => 'assistant', 'content' => 'That is great to hear.'],
    ],
    "add_generation_prompt" => true,
    "bos_token" => "",
    "eos_token" => "",
    "unk_token" => "",
];

$template = new Template($sourceString);
$rendered = $template->render($args);
// [INST] Hello! [/INST]Hi! How are you? [INST] I am doing great. [/INST]That is great to hear.
```

Features
--------

[](#features)

### ✅ **Supported Features**

[](#-supported-features)

#### **Control Structures**

[](#control-structures)

- **Conditional Statements**: `{% if %}`, `{% elif %}`, `{% else %}`, `{% endif %}`
- **For Loops**: `{% for %}`, `{% else %}`, `{% endfor %}` with loop variables (`loop.index`, `loop.index0`, `loop.first`, `loop.last`, `loop.length`, `loop.previtem`, `loop.nextitem`)
- **Break/Continue**: `{% break %}`, `{% continue %}` for loop control
- **Ternary Expressions**: `{{ value if condition else other_value }}`

#### **Variables &amp; Data**

[](#variables--data)

- **Variable Output**: `{{ variable }}`
- **Negative Array Indexing**: `messages[-1]`, `array[-2]` (Python-style)
- **Object/Array Access**: `user.name`, `messages[0]['content']`
- **Null Literals**: `none`, `None`
- **Boolean Literals**: `true`, `false`, `True`, `False`
- **String Concatenation**: `{{ "Hello" ~ " " ~ "World" }}`

#### **Macros &amp; Functions**

[](#macros--functions)

- **Macros**: `{% macro name(arg1, arg2) %}...{% endmacro %}` with `{{ name() }}` calls
- **Function Calls**: `{{ function(arg1, arg2) }}`
- **Keyword Arguments**: `{{ function(param1=value1, param2=value2) }}`
- **Spread Arguments**: `{{ function(*args) }}`

#### **Filters**

[](#filters)

- **String Filters**: `lower`, `upper`, `title`, `capitalize`, `strip`, `lstrip`, `rstrip`
- **String Manipulation**: `replace`, `split`, `startswith`, `endswith`, `indent`
- **Array Filters**: `length`, `join`, `map`, `reverse`, `sort`
- **Data Filters**: `tojson`, `default`
- **Custom Filter Blocks**: `{% filter filter_name %}...{% endfilter %}`

#### **Advanced Features**

[](#advanced-features)

- **Comments**: `{# This is a comment #}`
- **Set Statements**: `{% set variable = value %}` and block sets `{% set variable %}{% endset %}`
- **Call Blocks**: `{% call macro_name() %}...{% endcall %}`
- **Exception Handling**: `{{ raise_exception('Error message') }}`
- **String Concatenation**: Multiple string literals and `~` operator

#### **Built-in Functions**

[](#built-in-functions)

- `range()`: Generate number sequences
- `raise_exception()`: Throw runtime exceptions
- `len()`: Get length of arrays/strings

### 🔄 **Partially Supported Features**

[](#-partially-supported-features)

- **Complex Expressions**: Most Jinja expressions work, but some edge cases may differ
- **Template Inheritance**: Basic support (limited)
- **Custom Filters**: Can be added via the Environment class
- **Whitespace Control**: Basic support with `{%-` and `-%}`

### ❌ **Not Yet Supported**

[](#-not-yet-supported)

- **Template Inheritance**: `{% extends %}`, `{% block %}`, `{% include %}`
- **Custom Functions**: User-defined functions
- **Advanced Filters**: Some complex filters like `groupby`, `batch`

Usage Examples
--------------

[](#usage-examples)

### **Conditional Statements**

[](#conditional-statements)

```
{% if user.isActive %}
  Hello, {{ user.name }}!
{% elif user.isGuest %}
  Hello, Guest!
{% else %}
  Please log in.
{% endif %}
```

### **For Loops with Loop Variables**

[](#for-loops-with-loop-variables)

```
{% for user in users %}
  {{ loop.index }} - {{ user.name }}
  {% if loop.first %}First user{% endif %}
  {% if loop.last %}Last user{% endif %}
{% else %}
  No users found.
{% endfor %}
```

### **Macros**

[](#macros)

```
{% macro format_user(user) %}

    {{ user.name|title }}
    {{ user.email|lower }}

{% endmacro %}

{{ format_user(current_user) }}
```

### **String Manipulation**

[](#string-manipulation)

```
{{ "Hello World!"|upper|replace("WORLD", "PHP") }}
{{ "  hello  "|strip|capitalize }}
{{ "apple,banana,cherry"|split(",")|join(" and ") }}
{{ "Hello" ~ " " ~ "World" }}
```

### **Array Operations**

[](#array-operations)

```
{% for item in items|sort %}
  {{ item }}
{% endfor %}

{{ messages[-1]['content'] }}  {# Last message #}
{{ array|length }}  {# Array length #}
```

### **Set Statements**

[](#set-statements)

```
{% set greeting = "Hello, " ~ user.name %}
{{ greeting }}

{% set user_info %}
  Name: {{ user.name }}
  Email: {{ user.email }}
{% endset %}
{{ user_info|indent(2) }}
```

### **Filter Blocks**

[](#filter-blocks)

```
{% filter upper %}
  This text will be uppercase
{% endfilter %}
```

### **Comments**

[](#comments)

```
{# This is a comment that won't appear in output #}
{{ variable }}  {# Inline comment #}
```

Advanced Usage
--------------

[](#advanced-usage)

### **Error Handling**

[](#error-handling)

```
{% if user.role == 'admin' %}
  Admin panel
{% else %}
  {{ raise_exception('Access denied') }}
{% endif %}
```

### **Complex Expressions**

[](#complex-expressions)

```
{{ (user.isActive and user.hasPermission) or user.isAdmin }}
{{ messages|length > 0 and messages[-1].role == 'user' }}
{{ "Hello" if user.name else "Guest" }}
```

Testing
-------

[](#testing)

Jinja PHP comes with a comprehensive test suite to ensure functionality remains consistent and reliable. To run the tests:

```
composer test
```

The test suite includes:

- Unit tests for all language features
- End-to-end template processing tests
- Error handling and edge case tests

Performance
-----------

[](#performance)

Jinja PHP is designed for performance with:

- Zero external dependencies
- Efficient tokenization and parsing
- Optimized runtime execution
- Memory-conscious design

Contributing
------------

[](#contributing)

Jinja PHP is designed to be robust and feature-rich, offering support for a wide range of functionalities. If there's a feature you need that isn't currently implemented, we encourage you to [request it](https://github.com/codewithkyrian/jinja-php/issues/new). Additionally, if you're proficient with PHP and understand the internals of templating engines, consider contributing to the project by submitting a pull request with your proposed feature.

Contributors
------------

[](#contributors)

- [Kyrian Obikwelu](https://github.com/CodeWithKyrian)
- Other contributors are welcome.

Acknowledgements
----------------

[](#acknowledgements)

- [Hugging Face](https://huggingface.co/) for their work on ML chat templates.
- The Jinja template engine for Python, which served as the primary inspiration for this project.

Support
-------

[](#support)

If you find any issues or have a question, feel free to [open an issue](https://github.com/CodeWithKyrian/jinja-php/issues/new/choose) in the repo.

License
-------

[](#license)

This project is licensed under the MIT License. See the [LICENSE](https://github.com/CodeWithKyrian/jinja-php/blob/main/LICENSE) file for more information.

###  Health Score

47

—

FairBetter than 94% of packages

Maintenance64

Regular maintenance activity

Popularity43

Moderate usage in the ecosystem

Community16

Small or concentrated contributor base

Maturity52

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 90.5% 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 ~293 days

Total

3

Last Release

203d ago

Major Versions

1.0.0 → 2.0.02025-07-20

### Community

Maintainers

![](https://www.gravatar.com/avatar/146c2eb02350558d165083e0018f5377f15f0e71493439c93ee60e7c7ac97fc1?d=identicon)[CodeWithKyrian](/maintainers/CodeWithKyrian)

---

Top Contributors

[![CodeWithKyrian](https://avatars.githubusercontent.com/u/48791154?v=4)](https://github.com/CodeWithKyrian "CodeWithKyrian (19 commits)")[![dkeetonx](https://avatars.githubusercontent.com/u/16461516?v=4)](https://github.com/dkeetonx "dkeetonx (1 commits)")[![drjamesj](https://avatars.githubusercontent.com/u/37321814?v=4)](https://github.com/drjamesj "drjamesj (1 commits)")

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/codewithkyrian-jinja-php/health.svg)

```
[![Health](https://phpackages.com/badges/codewithkyrian-jinja-php/health.svg)](https://phpackages.com/packages/codewithkyrian-jinja-php)
```

###  Alternatives

[roots/acorn

Framework for Roots WordPress projects built with Laravel components.

9682.1M97](/packages/roots-acorn)[whitecube/nova-flexible-content

Flexible Content &amp; Repeater Fields for Laravel Nova.

8053.0M25](/packages/whitecube-nova-flexible-content)[mopa/bootstrap-bundle

Easy integration of twitters bootstrap into symfony2

7042.9M33](/packages/mopa-bootstrap-bundle)[limenius/react-bundle

Client and Server-side react rendering in a Symfony Bundle

3871.2M](/packages/limenius-react-bundle)[nicmart/string-template

StringTemplate is a very simple string template engine for php. I've written it to have a thing like sprintf, but with named and nested substutions.

2101.7M30](/packages/nicmart-string-template)[symfony/ux-icons

Renders local and remote SVG icons in your Twig templates.

555.8M69](/packages/symfony-ux-icons)

PHPackages © 2026

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