https://github.com/devknown/twig-import-function
Call (almost) any PHP function from your Twig (v3) templates.
https://github.com/devknown/twig-import-function
Last synced: 2 months ago
JSON representation
Call (almost) any PHP function from your Twig (v3) templates.
- Host: GitHub
- URL: https://github.com/devknown/twig-import-function
- Owner: devknown
- License: mit
- Created: 2022-07-02T00:56:22.000Z (almost 3 years ago)
- Default Branch: main
- Last Pushed: 2022-07-02T02:01:25.000Z (almost 3 years ago)
- Last Synced: 2025-03-15T17:48:43.343Z (2 months ago)
- Language: PHP
- Size: 14.6 KB
- Stars: 5
- Watchers: 1
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# Twig v3 Import Function
[](https://github.com/devknown/twig-import-function/actions?query=branch%3Amain)
[](https://packagist.org/packages/devknown/twig-import-function)Call (almost) any PHP function from your Twig (v3) templates.
## Requirements
PHP 7.3 and later.
Twig 3.x## Composer
You can install the bindings via [Composer](http://getcomposer.org/). Run the following command:
```bash
composer require devknown/twig-import-function
```To use the bindings, use Composer's [autoload](https://getcomposer.org/doc/01-basic-usage.md#autoloading):
```php
require_once('vendor/autoload.php');
```## Manual Installation
If you do not wish to use Composer, you can download and include the `ImportFunctionExtension.php` file.
```php
require_once('./src/Devknown/Twig/Extension/ImportFunctionExtension.php');
```## Getting Started
Simple usage looks like:
```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']);
```the template file `home.html` (/path/to/template/home.html) would look like:
```html
Hi, I am unique: {{ uniqid() }}.
{{ my_custom_function('Devknown') }}
```