PHPackages                             ali-translator/text-template - 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. [Utility &amp; Helpers](/categories/utility)
4. /
5. ali-translator/text-template

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

ali-translator/text-template
============================

Text templates

v1.2.1(4mo ago)11.6k1MITPHPPHP &gt;=7.4 &lt;8.5

Since Jul 12Pushed 4mo ago2 watchersCompare

[ Source](https://github.com/ali-translator/text-template)[ Packagist](https://packagist.org/packages/ali-translator/text-template)[ RSS](/packages/ali-translator-text-template/feed)WikiDiscussions master Synced yesterday

READMEChangelog (10)Dependencies (2)Versions (18)Used By (1)

Text template
=============

[](#text-template)

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

[](#installation)

This installation requires php &gt;=7.4 &lt;8.5

```
$ composer require ali-translator/text-template:^1
```

### Using

[](#using)

```
use \ALI\TextTemplate\MessageFormat\MessageFormatsEnum;
use \ALI\TextTemplate\TextTemplateFactory;

$textTemplateFactory = new TextTemplateFactory(new TemplateMessageResolverFactory('en'));

# Simple variable
$textTemplate = $textTemplateFactory->create('Tom has {appleNumbers} apples', [
    'appleNumbers' => 5,
]);
echo $textTemplate->resolve();
// Result: "Tom has 5 apples"

# Access nested values from associative arrays
$textTemplate = $textTemplateFactory->create('{SelectedProviderService.unique_name_for_contract}', [
    'SelectedProviderService' => [
        'unique_name_for_contract' => 'provider-contract-1',
    ],
]);
echo $textTemplate->resolve();
// Result: "provider-contract-1"

# For better results, you can add plural form selection
$textTemplate = $textTemplateFactory->create('Tom has {plural(appleNumbers, "=0[no apples] =1[one apple] other[many apples]")}', [
    'appleNumbers' => 1,
]);
echo $textTemplate->resolve();
// Result: "Tom has one apple"

# It is also possible to create multi-nested templates
$textTemplate = $textTemplateFactory->create('Tom has {appleNumbers}', [
    'appleNumbers' => [
        'content' => '{plural(appleNumbers,"=0[no apples] =1[one apple] other[many apples]")}',
        'parameters' => [
            'appleNumbers' => 1,
        ],
        // Custom values, if required (mostly for add-on libraries)
        'options' => ['some_notes' => 123]
    ],
]);
echo $textTemplate->resolve();
// Result: "Tom has one apple"

# The same effect will occur when using PHP objects
$insideTextTemplate = $textTemplateFactory->create(
    '{plural(appleNumbers,"=0[no apples] =1[one apple] other[many apples]")}',
    ['appleNumbers' => 1],
    MessageFormatsEnum::TEXT_TEMPLATE,
    ['some_notes' => 123]
);
$textTemplate = $textTemplateFactory->create('Tom has {appleNumbers}', [
    'appleNumbers' => $insideTextTemplate,
]);
// Result: "Tom has one apple"

// A modifier that is called after resolution
$templateItem = $textTemplateFactory->create('Tom has {appleNumbers} apples', [
    'appleNumbers' => 5,
], MessageFormatsEnum::TEXT_TEMPLATE, [
    TextTemplateItem::OPTION_AFTER_RESOLVED_CONTENT_MODIFIER => function (?string $text) {
        return str_replace(5, 3, $text);
    }
]);
// Result: "Tom has 3 apples"
```

### Conditional nodes

[](#conditional-nodes)

Use Twig-like block tags for conditional branches. Inside a node body you can keep using `{variable}` and function syntax.

```
$content = '{% if is_daytime %}\n  Good day, {user_name}!\n{% else %}\n  Good evening, {user_name}!\n{% endif %}';
$textTemplate = $textTemplateFactory->create($content, [
    'user_name' => 'Jerry',
    'is_daytime' => true,
]);
echo $textTemplate->resolve();
// Result: "\n  Good day, Jerry!\n" (whitespace preserved)
```

Conditions support simple expressions like:

```
{% if online == false %}...{% endif %}
{% if product_stock > 10 %}...{% elseif product_stock > 0 %}...{% else %}...{% endif %}

```

### Loop nodes

[](#loop-nodes)

Loop through arrays using `{% for item in items %}` and `{% endfor %}`. Dot-path variables (`{a.b.c}`) work both outside and inside loops.

```
$content = '{% for user in users %}{print(user.name)|makeFirstCharacterInUppercase()} ({user.city}) {% endfor %}';
$textTemplate = $textTemplateFactory->create($content, [
    'users' => [
        ['name' => 'tom', 'city' => 'london'],
        ['name' => 'kate', 'city' => 'rome'],
    ],
]);
echo $textTemplate->resolve();
// Result: "Tom (london) Kate (rome) "
```

### Functions Syntax

[](#functions-syntax)

In our system, Functions provide a dynamic way to manipulate and format text. They utilize a syntax that closely resembles the pipe functionality in Unix-based systems, allowing for a chained or sequential application of multiple functions.

#### Basic Syntax:

[](#basic-syntax)

`{functionName(some_variable_name, 'some static text')|anotherFunctionWithoutArguments()}`

[More details about the syntax](./guides/FUNCTIONS_SYNTAX.md)

### Handlers that process Functions

[](#handlers-that-process-functions)

Handlers are the core functionalities behind the Function Syntax. They offer the ability to manipulate text and data in various ways.

#### Handlers available out of the box:

[](#handlers-available-out-of-the-box)

- **PrintHandler**: Prints the value of a "static"/"plain variable". Can be used as input to another handler function. `{print('Hello World')}`
- **HideHandler**: This handler is designed to acknowledge variables without displaying them in the text. This can be useful in situations where you need to ensure that all registered variables are used in the text, even if they don't visibly appear.
    `{hide(variable1, variable2, ...)}`
- **PluralHandler**: Handles pluralization based on the given parameters and locale.
    `{plural(appleNumbers,"=0[no one apple] =1[one apple] other[many apples]")}`
- **FirstCharacterInLowercaseHandler**: Changes the first character of the input string to lowercase.
    `{print('HELLO')|makeFirstCharacterInLowercase()}`
- **FirstCharacterInUppercaseHandler**: Transforms the first character of the given text to uppercase.
    `{print('hello')|makeFirstCharacterInUppercase()}`
- **ChoosePrepositionBySonorityHandler (Russian)**: Determines the correct preposition for the given word in Russian.
    `Поездка {ru_choosePreposition('во/в', 'Львов')} Львов`
- **AddLocativeSuffixHandler (Turkish)**: Appends the correct locative suffix to a given word in Turkish.
    `{tr_addLocativeSuffix('İstanbul')}` -&gt; `İstanbul'da`
- **AddDirectionalSuffixHandler (Turkish)**: Adds the appropriate directional suffix ("'a", "'e", "'ya", "'ye") to the given word based on vowel harmony.
    `{tr_addDirectionalSuffix('İstanbul')}` -&gt; `İstanbul'a`
    Without apostrophe:
    `{tr_addDirectionalSuffix('Ev', '')}` -&gt; `Eve`
- **ChooseQuestionSuffixHandler (Turkish)**: Chooses the appropriate question suffix ("mı", "mi", "mu", "mü") for the given word based on vowel harmony. Specific to the Turkish language.
    `Şehriniz {city_name} {tr_chooseQuestionSuffix(city_name)}?` results for "İstanbul" will be `Şehriniz İstanbul mu?`
- **ChoosePrepositionBySonorityHandler (Ukrainian)**: Determines the correct preposition for the given word in Ukrainian.
    `Поїздка {uk_choosePreposition('Поїздка', 'в/у', 'Львів')} Львів`

### Tests

[](#tests)

```
php composer install
./vendor/bin/phpunit
```

###  Health Score

48

—

FairBetter than 93% of packages

Maintenance76

Regular maintenance activity

Popularity18

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity74

Established project with proven stability

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

Recently: every ~117 days

Total

16

Last Release

129d ago

Major Versions

v0.3.1 → v1.0.02023-09-27

PHP version history (2 changes)v0.1.0PHP ^7.4

v1.1.1PHP &gt;=7.4 &lt;8.5

### Community

Maintainers

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

---

Top Contributors

[![Slayer911](https://avatars.githubusercontent.com/u/9704032?v=4)](https://github.com/Slayer911 "Slayer911 (27 commits)")

---

Tags

ALIslitext templates

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/ali-translator-text-template/health.svg)

```
[![Health](https://phpackages.com/badges/ali-translator-text-template/health.svg)](https://phpackages.com/packages/ali-translator-text-template)
```

PHPackages © 2026

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