Jinja for PHP is a PHP implementation of the Jinja2 template engine.
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.
Currently, the following features are implemented:
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.
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.
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 }}
{{ 1 + 2 }}
{{ 1 - 2 }}
{{ 1 * 2 }}
{{ 1 / 2 }}
{{ 1 % 2 }}
{{ 1 ** 2 }}
{{ "Hello" ~ "World" }}
{{ var1 ~ var2 }}
{{ 1 == 2 }}
{{ 1 != 2 }}
{{ 1 < 2 }}
{{ 1 <= 2 }}
{{ 1 > 2 }}
{{ 1 >= 2 }}
There are some differences between the Python and PHP implementation.
TODO: use and
and or
instead of &&
and ||
{{ 1 && 2 }}
{{ 1 || 2 }}
{{ ! 1 }}
@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 %}
@todo: else
is not implemented yet.
{% for item in items %}
{{ item }}
{% endfor %}
{% for key, value in items %}
{{ key }}: {{ value }}
{% endfor %}
Loop control variable:
{% for item in items %}
{{ loop.index }}: {{ item }}
{% endfor %}
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);
composer require byjg/jinja-php
flowchart TD
byjg/jinja-php