devknown/twig-import-function

从您的Twig(v3)模板中调用(几乎)任何PHP函数。

1.0.0 2022-07-02 01:54 UTC

This package is auto-updated.

Last update: 2024-08-30 01:26:35 UTC


README

Build Status License

从您的Twig(v3)模板中调用(几乎)任何PHP函数。

要求

PHP 7.3及更高版本。Twig 3.x

Composer

您可以通过Composer安装这些绑定。运行以下命令:

composer require devknown/twig-import-function

要使用这些绑定,请使用Composer的自动加载功能。

require_once('vendor/autoload.php');

手动安装

如果您不想使用Composer,可以下载并包含ImportFunctionExtension.php文件。

require_once('./src/Devknown/Twig/Extension/ImportFunctionExtension.php');

入门指南

简单用法如下

// 1. Setup twig 3.x
$loader = new \Twig\Loader\FilesystemLoader('/path/to/template');
$twig = new \Twig\Environment($loader);

// 2. Load extension
$extension = new \Devknown\Twig\Extension\ImportFunctionExtension();

// 3. Import a function
$extension->import('uniqid');

// -> Or multiple functions
function my_custom_function($name) {
    echo "Your name is: " . $name;
}
$extension->import(['uniqid', 'file_exists', 'my_custom_function']);
// Note: in this example, the 'my_custom_function..' must be accessible globally 

// 4. Add extension
$twig->addExtension($extension);

// 5. Render as normal
echo $twig->render('home.html', ['the' => 'variables', 'go' => 'here']);

模板文件home.html (/path/to/template/home.html)将看起来像这样:

<div>
    Hi, I am unique: <b>{{ uniqid() }}</b>.
    <br/> 
    {{ my_custom_function('Devknown') }}
</div>