claserre9/twig-for-slim

Twig template for slim microframework

Installs: 0

Dependents: 0

Suggesters: 0

Security: 0

Stars: 0

Watchers: 0

Forks: 0

Open Issues: 0

pkg:composer/claserre9/twig-for-slim

dev-master 2026-01-16 15:22 UTC

This package is auto-updated.

Last update: 2026-01-16 15:43:27 UTC


README

A Twig template integration for the Slim 4 microframework. This library provides a simple wrapper for Twig, a Slim middleware for easy integration, and a Twig extension for Slim-specific functions (like generating URLs from routes).

Overview

This project allows you to quickly set up Twig as the template engine for your Slim 4 application. It includes:

  • A Twig wrapper class for managing the Twig environment.
  • TwigMiddleware to inject the Twig instance into Slim requests.
  • TwigExtension providing useful functions like url_for inside your Twig templates.

Requirements

  • PHP: ^7.4 || ^8.0
  • Slim Framework: ^4.0
  • Twig: ^3.0
  • Guzzle HTTP PSR-7: ^2.0

Installation

Install the package via Composer:

composer require claserre9/twig-for-slim

Basic Usage

Below is a basic example of how to integrate Twig into your Slim 4 application.

1. Setup in index.php

<?php
use Slim\Factory\AppFactory;
use Claserre9\TwigForSlim\Twig;
use Claserre9\TwigForSlim\middlewares\TwigMiddleware;

require __DIR__ . '/vendor/autoload.php';

$app = AppFactory::create();

// Create Twig instance
$twig = Twig::create(__DIR__ . '/templates', [
    'cache' => __DIR__ . '/cache',
]);

// Add Slim's Routing Middleware (required for url_for and other route helpers)
$app->addRoutingMiddleware();

// Add Twig Middleware to the app
$app->add(TwigMiddleware::create($app, $twig));

// Define a route
$app->get('/hello/{name}', function ($request, $response, $args) {
    // Access Twig from the request attribute
    $twig = $request->getAttribute('twig');
    
    $payload = $twig->render('hello.twig', [
        'name' => $args['name']
    ]);
    
    $response->getBody()->write($payload);
    return $response;
})->setName('hello');

$app->run();

2. Usage with DI Container (Recommended)

If you use a DI container (like PHP-DI), you can register Twig as a service.

use Psr\Container\ContainerInterface;
use Claserre9\TwigForSlim\Twig;
use Claserre9\TwigForSlim\middlewares\TwigMiddleware;
use Slim\Factory\AppFactory;

// ... container setup ...
$container->set(Twig::class, function () {
    return Twig::create(__DIR__ . '/templates');
});

AppFactory::setContainer($container);
$app = AppFactory::create();

// The middleware will automatically fetch Twig from the container
$app->add(TwigMiddleware::create($app, Twig::class));

3. Create a Template (templates/hello.twig)

<!DOCTYPE html>
<html>
<head>
    <title>Hello Page</title>
</head>
<body>
    <h1>Hello, {{ name }}!</h1>
    <p>Go to <a href="{{ url_for('hello', {'name': 'world'}) }}">World</a></p>
</body>
</html>

Twig Extension Functions

The following functions are available within your Twig templates thanks to TwigExtension:

Function Description Example
url_for(name, data, params) Generates a URL for a named route. {{ url_for('hello', {'name': 'world'}) }}
full_url_for(name, data, params) Generates a fully qualified URL for a named route. {{ full_url_for('hello', {'name': 'world'}) }}
path(name, data, relative) Alias for url_for. If relative is true, it returns a relative path. {{ path('home') }}
url(name, data, schemeRelative) Generates a URL for a named route. {{ url('home') }}
relative_path(path) Returns a relative path from the current URI to the given path. {{ relative_path('/assets/css/style.css') }}
base_path() Returns the base path of the Slim application. {{ base_path() }}

Advanced Usage

Custom Filters and Functions

You can add custom filters or functions directly to the TwigExtension via the Twig instance:

use Claserre9\TwigForSlim\TwigExtension;
use Twig\TwigFilter;
use Twig\TwigFunction;

$twig = Twig::create(__DIR__ . '/templates');

// ... after middleware is added and extension is initialized (usually in route or another middleware)
// OR manually get the extension from environment:
$environment = $twig->getEnvironment();
$extension = $environment->getExtension(TwigExtension::class);

$extension->addFunction(new TwigFunction('my_func', function() { ... }));
$extension->addFilter(new TwigFilter('my_filter', function($val) { ... }));

Runtime Loaders

If you have complex dependencies for your Twig extensions, you can use Runtime Loaders:

$twig = Twig::create(__DIR__ . '/templates');
$twig->addRuntimeLoader(new MyCustomRuntimeLoader());

Project Structure

twig-for-slim/
├── src/
│   ├── Twig.php               # Twig Environment wrapper
│   ├── TwigExtension.php      # Custom Twig functions for Slim
│   └── middlewares/
│       └── TwigMiddleware.php # Slim Middleware for Twig integration
├── templates/                 # (Optional) Your Twig templates
├── index.php                  # Example entry point
├── composer.json              # Project dependencies and autoloading
└── README.md                  # Project documentation

Scripts

You can run the following commands for development:

# Run tests
composer test

# Run static analysis
composer analyze

# Check coding standards
composer check-style

# Fix coding standards
composer fix-style

Tests

Tests are located in the tests/ directory and can be run with composer test.

License

This project is licensed under the MIT License. See the composer.json file for details.