定制 ali-translator/text-template 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

ali-translator/text-template

最新稳定版本:v1.2.1

Composer 安装命令:

composer require ali-translator/text-template

包简介

Text templates

README 文档

README

Installation

This installation requires php >=7.4 <8.5

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

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('<td>{SelectedProviderService.unique_name_for_contract}</td>', [
    'SelectedProviderService' => [
        'unique_name_for_contract' => 'provider-contract-1',
    ],
]);
echo $textTemplate->resolve();
// Result: "<td>provider-contract-1</td>"

# 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

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 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

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:

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

More details about the syntax

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:

  • 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')} -> İstanbul'da

  • AddDirectionalSuffixHandler (Turkish): Adds the appropriate directional suffix ("'a", "'e", "'ya", "'ye") to the given word based on vowel harmony.
    {tr_addDirectionalSuffix('İstanbul')} -> İstanbul'a
    Without apostrophe:
    {tr_addDirectionalSuffix('Ev', '')} -> 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

php composer install
./vendor/bin/phpunit

统计信息

  • 总下载量: 1.57k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 1
  • 点击次数: 1
  • 依赖项目数: 1
  • 推荐数: 0

GitHub 信息

  • Stars: 1
  • Watchers: 2
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2022-07-12

承接程序开发

PHP开发

VUE

Vue开发

前端开发

小程序开发

公众号开发

系统定制

数据库设计

云部署

网站建设

安全加固