PHPackages                             zenstruck/twig-service-bundle - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Templating &amp; Views](/categories/templating)
4. /
5. zenstruck/twig-service-bundle

ActiveSymfony-bundle[Templating &amp; Views](/categories/templating)

zenstruck/twig-service-bundle
=============================

Make functions, static methods, Symfony service methods available in your twig templates.

v1.6.0(5mo ago)1310.1k↓38.5%3[1 PRs](https://github.com/zenstruck/twig-service-bundle/pulls)MITPHPPHP &gt;=8.0CI failing

Since Nov 9Pushed 3mo ago1 watchersCompare

[ Source](https://github.com/zenstruck/twig-service-bundle)[ Packagist](https://packagist.org/packages/zenstruck/twig-service-bundle)[ Docs](https://github.com/zenstruck/twig-service-bundle)[ GitHub Sponsors](https://github.com/kbond)[ GitHub Sponsors](https://github.com/nikophil)[ RSS](/packages/zenstruck-twig-service-bundle/feed)WikiDiscussions 1.x Synced 1mo ago

READMEChangelog (10)Dependencies (9)Versions (14)Used By (0)

zenstruck/twig-service-bundle
=============================

[](#zenstrucktwig-service-bundle)

[![CI](https://github.com/zenstruck/twig-service-bundle/actions/workflows/ci.yml/badge.svg)](https://github.com/zenstruck/twig-service-bundle/actions/workflows/ci.yml)[![codecov](https://camo.githubusercontent.com/fb9182d146d7d507e5dfe8af65381ca4db021329a5eed8926cf935728378f3b2/68747470733a2f2f636f6465636f762e696f2f67682f7a656e73747275636b2f747769672d736572766963652d62756e646c652f6272616e63682f312e782f67726170682f62616467652e7376673f746f6b656e3d5a4b3158534736583335)](https://codecov.io/gh/zenstruck/twig-service-bundle)

Making data from your app's services available in twig templates can be done by either:

1. Injecting the service/data into the template when rendering.
2. Creating a twig extension that has access to the service/data.

For #1, this isn't always a viable option (ie you need this data in your layout). With #2, there is a bit of boilerplate and if done incorrectly (ie not using a [runtime](https://symfony.com/doc/current/templating/twig_extension.html#creating-lazy-loaded-twig-extensions)or [service proxy](https://symfony.com/doc/current/service_container/lazy_services.html)for heavy services), it could lead to performance issues.

This bundle provides an easy way to make functions, static methods, service methods, and even full service objects available in your twig templates.

Installation
------------

[](#installation)

```
composer require zenstruck/twig-service-bundle
```

Note

If not added automatically by `symfony/flex`, enable `ZenstruckTwigServiceBundle`.

Usage
-----

[](#usage)

Note

The output for the following functions/filters will be escaped. If your function\\filter returns html that you don't want escaped, use the `|raw` filter.

### Service Methods as Functions/Filters

[](#service-methods-as-functionsfilters)

You can mark any public method in your configured services with the `#[AsTwigFunction]`attribute to make them available within your twig templates with the `fn()` twig function/filter:

```
// ...
use Zenstruck\Twig\AsTwigFunction;

class SomeService
{
    // ...

    #[AsTwigFunction] // will be available as "fn_someMethod()" in twig
    public function someMethod($arg1, $arg2): string
    {
        // ...
    }

    #[AsTwigFunction('alias')] // will be available as "fn_alias()" in twig
    public function anotherMethod($arg1, $arg2): string
    {
        // ...
    }
}
```

In your twig template, use the `fn()` function/filter to call:

```
{# as a function: #}
{{ fn('someMethod', 'foo', 'bar') }}
{{ fn('alias', 'foo', 'bar') }}

{# as a filter: #}
{{ 'foo'|fn('someMethod', 'bar') }}
{{ 'foo'|fn('alias', 'bar') }}
```

*Dynamic* functions/filters are made available. The following is equivalent to above:

```
{# as a function: #}
{{ fn_someMethod('foo', 'bar') }}
{{ fn_alias('foo', 'bar') }}

{# as a filter: #}
{{ 'foo'|fn_someMethod('bar') }}
{{ 'foo'|fn_alias('bar') }}
```

### User Defined as Functions/Filters

[](#user-defined-as-functionsfilters)

You can mark any of your custom functions with the `#[AsTwigFunction]` attribute to make them available within your twig templates with the `fn()` twig function\\filter:

```
use Zenstruck\Twig\AsTwigFunction;

#[AsTwigFunction] // will be available as "some_function" in twig
function some_function($arg1, $arg2): string
{
    // ...
}

#[AsTwigFunction('alias')] // will be available as "alias" in twig
function another_function($arg1, $arg2): string
{
    // ...
}
```

In your twig template, use the `fn()` function/filter to call:

```
{# as a function: #}
{{ fn('some_function', 'foo', 'bar') }}
{{ fn('alias', 'foo', 'bar') }}

{# as a filter: #}
{{ 'foo'|fn('some_function', 'bar') }}
{{ 'foo'|fn('alias', 'bar') }}
```

*Dynamic* functions/filters are made available. The following is equivalent to above:

```
{# as a function: #}
{{ fn_some_function('foo', 'bar') }}
{{ fn_alias('foo', 'bar') }}

{# as a filter: #}
{{ 'foo'|fn_some_function('bar') }}
{{ 'foo'|fn_alias('bar') }}
```

#### 3rd-Party Functions/Filters

[](#3rd-party-functionsfilters)

If you need to make functions, static/service methods available in your twig templates for code you do not control (ie internal PHP functions/3rd party package), you can configure these in the bundle config:

```
zenstruck_twig_service:
    functions:
        - strlen # available as "fn_strlen()" in twig
        - [service.id, serviceMethod] # available as "fn_serviceMethod()" in twig
        - [Some\Class, somePublicStaticMethod] # available as "fn_somePublicStaticMethod()" in twig

    # use the array key to customize the name
    functions:
        len: strlen # available as "fn_len()" in twig
        custom: [service.id, serviceMethod] # available as "fn_custom()" in twig
        alias: [Some\Class, somePublicStaticMethod] # available as "fn_alias()" in twig
```

### Service Function

[](#service-function)

Mark any service you'd like to make available in twig templates with the `#[AsTwigService]`.

Note

While you can mark any service as a *twig service*, it is not recommended to mark services that have nothing to do with templating (ie repositories) as such. You can think of twig services as *lightweight-lazy-twig-extension-functions* whose purpose is to break up/simplify large custom twig extensions.

```
namespace App\Twig\Service;

// ...
use Zenstruck\Twig\AsTwigService;

#[AsTwigService(alias: 'posts')]
class PostService
{
    public function __construct(private PostRepository $repo)
    {
    }

    /**
     * @return Post[]
     */
    public function latestPosts(int $number = 10): array
    {
        return $this->repo->findLatestPosts($number);
    }
}
```

You're now ready to access the service in any twig template:

```
{% for post in service('posts').latestPosts(5) %}
    {# ... #}
{% endfor %}
```

Each service alias is made available as a *dynamic* function. The following is equivalent to above:

```
{% for post in service_posts().latestPosts(5) %}
    {# ... #}
{% endfor %}
```

### Invokable Service Filters

[](#invokable-service-filters)

You can turn any twig service into a twig filter by having it implement `__invoke()`:

```
namespace App\Twig\Service;

// ...
use Zenstruck\Twig\AsTwigService;

#[AsTwigService(alias: 'image_transformer')]
class ImageTransformer
{
    public function __invoke(string $imageUrl, string ...$transformations): string
    {
        // adds transformation to url and returns new url
    }
}
```

In your template, use the `service` twig filter:

```
{{ url|service('image_transformer', 'square-200', 'watermark') }}
```

Each service alias is made available as a *dynamic* filter. The following is equivalent to above:

```
{{ url|service_image_transformer('square-200', 'watermark') }}
```

### Parameter Function

[](#parameter-function)

You can access any service container parameter with the provided `parameter()`twig function:

```
{% for locale in parameter('kernel.enabled_locales') %}
    {# ... #}
{% endfor %}
```

### `zenstruck:twig-service:list` Command

[](#zenstrucktwig-servicelist-command)

Use this command to list all functions/filters/services configured by this bundle and available in your twig templates.

Note

This command is only available when `debug: true`.

```
bin/console zenstruck:twig-service:list

Available Functions/Filters
---------------------------

 // As function: call with fn('{alias}', {...args}) or fn_{alias}({...args})

 // As filter: use as {value}|fn('{alias}', {...args}) or {value}|fn_{alias}({...args})

 ---------- ---------------------------------------------
  Alias      Callable
 ---------- ---------------------------------------------
  strlen     strlen
  generate   @router->generate()
 ---------- ---------------------------------------------

Available Services
------------------

 // Access via service('{alias}') or service_{alias}()

 // If invokable, use as {value}|service('{alias}', {...args}) or {value}|service_{alias}({...args})

 ------- -------------------- ------------
  Alias   Service              Invokable?
 ------- -------------------- ------------
  foo     App\SomeService      yes
  bar     App\AnotherService   no
 ------- -------------------- ------------

```

Full Default Bundle Configuration
---------------------------------

[](#full-default-bundle-configuration)

```
zenstruck_twig_service:

    # Callables to make available with fn() twig function/filter
    functions:

        # Examples:
        0:                   strlen # available as "strlen"
        alias:               [Some\Class, somePublicStaticMethod] # available as "alias"
```

###  Health Score

50

—

FairBetter than 96% of packages

Maintenance78

Regular maintenance activity

Popularity34

Limited adoption so far

Community11

Small or concentrated contributor base

Maturity62

Established project with proven stability

 Bus Factor1

Top contributor holds 96.3% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~120 days

Recently: every ~269 days

Total

14

Last Release

92d ago

Major Versions

v0.2.0 → v1.0.02022-11-11

PHP version history (2 changes)v0.1.0PHP &gt;=7.4

v1.0.0PHP &gt;=8.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/707369cc916e0ea1aacbf077dcba464f611cef879f024d8944311a54a15224b3?d=identicon)[kbond](/maintainers/kbond)

---

Top Contributors

[![kbond](https://avatars.githubusercontent.com/u/127811?v=4)](https://github.com/kbond "kbond (52 commits)")[![tacman](https://avatars.githubusercontent.com/u/619585?v=4)](https://github.com/tacman "tacman (2 commits)")

---

Tags

twigdependency-injectionservice

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/zenstruck-twig-service-bundle/health.svg)

```
[![Health](https://phpackages.com/badges/zenstruck-twig-service-bundle/health.svg)](https://phpackages.com/packages/zenstruck-twig-service-bundle)
```

###  Alternatives

[twig/extra-bundle

A Symfony bundle for extra Twig extensions

91492.0M315](/packages/twig-extra-bundle)[symfony/ux-icons

Renders local and remote SVG icons in your Twig templates.

555.8M69](/packages/symfony-ux-icons)[yellowskies/qr-code-bundle

Symfony Barcode &amp; QR Code Generator Bundle with Twig extension

36682.9k](/packages/yellowskies-qr-code-bundle)[symfony/ux-toolkit

A tool to easily create a design system in your Symfony app with customizable, well-crafted Twig components

1432.0k](/packages/symfony-ux-toolkit)[boekkooi/jquery-validation-bundle

Jquery form validation bundle for symfony 2

2773.9k1](/packages/boekkooi-jquery-validation-bundle)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
