Search by

byjg / jinja-php

byjg

Lightweight PHP implementation of the Jinja2 template engine originally developed for Python

Package info

github.com/byjg/php-jinja

pkg:composer/byjg/jinja-php

Statistics

Installs: 58 031

Dependents: 3

Suggesters: 0

Stars: 16

Open Issues: 1

6.0.0 2025-11-22 01:36 UTC

This package is auto-updated.

Last update: 2026-10-25 23:49:52 UTC


README

sidebar_key jinja
sidebar_category text-content
tags
php text-manipulation template

Jinja for PHP

Jinja2 templates in pure PHP: the same template renders in your Python and your PHP code.

Sponsor Build Status Opensource ByJG Install MCP Server GitHub source GitHub license GitHub release

Why

A team that has Python and PHP side by side ends up writing every email, report or configuration template twice, in two template languages, and keeping them in sync.

Jinja for PHP reads the Jinja2 syntax, so one template serves both:

$template = (new FileSystemLoader(__DIR__ . '/templates'))->getTemplate('welcome');
echo $template->render(['name' => 'World']);

Variables, conditions, loops, filters and expressions work as in Jinja2, with no extension or compiled cache to install. Template inheritance, includes and macros are not supported yet; see the comparison with Jinja2.

Overview

This library allows you to seamlessly process Jinja templates in PHP applications. It provides a familiar syntax for those coming from Python while offering a native PHP implementation.

Key Features

  • Python Compatibility: Process the same Jinja templates in both Python and PHP
  • Variable Support: Full support for variables, properties, and nested structures
  • Conditional Logic: if/elif/else statements for conditional rendering
  • Loops: Iterate over arrays and objects with for loops
  • Filters: Transform output with built-in filters like upper, lower, default, etc.
  • Flexible Loaders: Load templates from strings or the filesystem
  • Undefined Variable Handling: Different strategies for handling undefined variables
  • Expressions: Support for mathematical operations, comparisons, and concatenation

Usage

use ByJG\JinjaPhp\Template;
use ByJG\JinjaPhp\Undefined\DebugUndefined;

$templateString = <<<EOT
Hello {{ name }}
EOT;

$template = new Template($templateString);
$template->withUndefined(new DebugUndefined());  // Default is StrictUndefined

$variables = [
    'name' => 'World'
];
echo $template->render($variables);

Documentation

The detailed documentation is organized as follows:

  1. Basic Usage
  2. Template Syntax
  3. Loaders
  4. Undefined Variables
  5. Filters
  6. Control Structures
  7. Advanced Topics
  8. API Reference
  9. PHP Jinja vs Python Jinja2 Comparison

Installation

composer require byjg/jinja-php

Running Tests

vendor/bin/phpunit

Open source ByJG