byjg/jinja-php

Jinja for PHP

Fund package maintenance!
byjg

5.0.0 2024-10-29 22:33 UTC

This package is auto-updated.

Last update: 2024-10-29 22:35:57 UTC


README

Build Status Opensource ByJG GitHub source GitHub license GitHub release

Jinja for PHP is a PHP implementation of the Jinja2 template engine.

Introduction

This library is a port of the Jinja2 template engine to PHP. It is a partial implementation of the Jinja2 template engine.

The main goal of this library is allow process templates both in Jinja Python and PHP, however he API is not the same as the original in Python.

Implemented Features

Currently, the following features are implemented:

Literals

Most of the literals are supported. e.g.

{{ 1 }}
{{ 1.2 }}
{{ "Hello World" }}
{{ true }}
{{ false }}
{{ none }}
{{ [1, 2, 3] }}
{{ ['a': 1, 'b': 2] }}  // It is different from Python

@todo: use the python notation for dictionaries.

Variables

Most of the variables are supported. e.g.

{{ myvar }}
{{ myvar.myproperty }}
{{ myvar.myproperty.1 }}
{{ myvar.myproperty.a }}
{{ myvar.myproperty.a.myproperty }}
{{ myvar.myproperty.a.myproperty.1 }}
{{ myvar.myproperty.a.myproperty.1.myproperty }}

@todo: The notation with brackets is not yet supported.

Filters

Some filters are implemented:

{{ var | upper }}
{{ var | lower }}
{{ var | default }}
{{ var | default('-') }}
{{ var | replace('a', 'b') }}
{{ var | join }}
{{ var | join(',') }}
{{ var | split }}
{{ var | split(',') }}
{{ var | capitalize }}
{{ var | trim }}
{{ var | trim('-') }}
{{ var | length }}

Math Operations

{{ 1 + 2 }}
{{ 1 - 2 }}
{{ 1 * 2 }}
{{ 1 / 2 }}
{{ 1 % 2 }}
{{ 1 ** 2 }}

Concatenation

{{ "Hello" ~ "World" }}
{{ var1 ~ var2 }}

Comparison

{{ 1 == 2 }}
{{ 1 != 2 }}
{{ 1 < 2 }}
{{ 1 <= 2 }}
{{ 1 > 2 }}
{{ 1 >= 2 }}

Logic Operations

There are some differences between the Python and PHP implementation. TODO: use and and or instead of && and ||

{{ 1 && 2 }}
{{ 1 || 2 }}
{{ ! 1 }}

If

@todo: elif is not implemented yet.

{% if var1 == var2 %}
    {{ var1 }} is equal to {{ var2 }}
{% else %}
    1 is not equal to 2 or 3
{% endif %}
{% if 1 == 2 %}
    1 is equal to 2
{% else %}
    1 is not equal to 2 or 3
{% endif %}

For

@todo: else is not implemented yet.

{% for item in items %}
    {{ item }}
{% endfor %}
{% for key, value in items %}
    {{ key }}: {{ value }}
{% endfor %}

Loop control variable:

  • loop.index
  • loop.index0
  • loop.revindex
  • loop.revindex0
  • loop.first
  • loop.last
  • loop.length
{% for item in items %}
    {{ loop.index }}: {{ item }}
{% endfor %}

Usage

use ByJG\JinjaPhp\Template;

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

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

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

Installation

composer require byjg/jinja-php

Dependencies

Open source ByJG