germania-kg/twigextensions

Germania KG's extensions for the Twig template engine.

2.0.0 2019-11-25 11:15 UTC

This package is auto-updated.

Last update: 2024-03-25 21:08:03 UTC


README

Germania KG's extensions for the Twig template engine. Comes for now with exactly one Twig Extension: WebAppTwigExtension

Requirements

• Twig template Engine twig/twig Release 2 or 3

Built-Ins

When added to Twig_Environment, this WebAppTwigExtension brings these built-in helpers:

absolute_url

This test checks if a value is an absolute URL, i.e. begins with //, http:// or https:// 

{% if my_value is absolute_url %}

add_base_url

This filter prepends a base URL to a given value which does not begin with //, http:// or https:// 

{{my_var|add_base_url( base_url )}}

Installation

Grab from shell using Composer:

$ composer require germania-kg/twigextensions

Alternatively, add this package directly to your composer.json:

"require": {
    "germania-kg/twigextensions": "^2.0"
}

Usage

<?php
use Germania\TwigExtensions\WebAppTwigExtension;

# Instantiate
$gte = new WebAppTwigExtension();

# Add to Twig Environment
$twig = new Twig_Environment( ... );
$twig->addExtension( $gte );

Configuration

Tests, filters, and globals should normally be added to the Twig_Environment instance. In some situations you may prefer defining your helpers near the location where you instantiate this extension. In this case optionally provide custom filters, globals and tests on instantiation.

<?php
use Germania\TwigExtensions\WebAppTwigExtension;

$gte = new WebAppTwigExtension([
    'globals' => [
        'base_url' => 'http://test.com'
    ],
    'filters' => [
        new Twig_SimpleFilter('my_filter', function() { ...} )
    ],
    'tests' => [
    	new Twig_SimpleTest('my_test', function() { ... } )
    ]
]);

Fluent Interface API

Filters, Globals and Tests can be added right after instantiation. The setter methods return the instance:

<?php
use Germania\TwigExtensions\WebAppTwigExtension;

$gte = new WebAppTwigExtension();

$filter = new Twig_SimpleFilter('my_filter', function() { ...} );
$test   = new Twig_SimpleTest( ... );

$gte->addGlobal( 'foo', 'bar')
    ->addFilter( $filter );
    ->addTest( $test );

Development

$ git clone git@bitbucket.org:germania/twigextensions.git
$ cd twigextensions
$ composer install

Unit tests

Either copy phpunit.xml.dist to phpunit.xml and adapt to your needs, or leave as is. Run PhpUnit like this:

$ vendor/bin/phpunit