Giter Club home page Giter Club logo

mezzio-twigrenderer's Introduction

Twig Integration for Mezzio

Build Status

🇷🇺 Русским гражданам

Мы, участники Laminas, родились и живем в разных странах. У многих из нас есть друзья, родственники и коллеги как в России, так и в Украине. Некоторые из нас родились в России. Некоторые из нас живут в России. У некоторых бабушки и дедушки сражались с фашистами во Второй мировой войне. Здесь никто не поддерживает фашизм.

У одного из нас есть украинская родственница, которая спаслась из дома вместе с сыном. Поезд задержался из-за бомбежки на дороге впереди. У нас есть друзья, которые прячутся в бомбоубежищах. Мы с тревогой ждем весточки от них после воздушных налетов, которые беспорядочно наносят удары и попадают по больницам, школам, детским садам и домам. Мы не берем это из каких-либо СМИ. Мы наблюдаем это напрямую.

Вы доверяете нам достаточно, чтоб использовать наши программы, и мы просим вас довериться нам вновь. Мы нуждаемся в помощи. Выходите и протестуйте против этой бесполезной войны. Остановите кровопролитие. Скажите "Нет войне!"

🇺🇸 To Citizens of Russia

We at Laminas come from all over the world. Many of us have friends, family and colleagues in both Russia and Ukraine. Some of us were born in Russia. Some of us currently live in Russia. Some have grandparents who fought Nazis in World War II. Nobody here supports fascism.

One team member has a Ukrainian relative who fled her home with her son. The train was delayed due to bombing on the road ahead. We have friends who are hiding in bomb shelters. We anxiously follow up on them after the air raids, which indiscriminately fire at hospitals, schools, kindergartens and houses. We're not taking this from any media. These are our actual experiences.

You trust us enough to use our software. We ask that you trust us to say the truth on this. We need your help. Go out and protest this unnecessary war. Stop the bloodshed. Say "stop the war!"

Provides Twig integration for Mezzio.

Installation

Install this library using composer:

$ composer require mezzio/mezzio-twigrenderer

We recommend using a dependency injection container, and typehint against container-interop. We can recommend the following implementations:

Twig Extension

The included Twig extension adds support for url generation. The extension is automatically activated if the UrlHelper and ServerUrlHelper are registered with the container.

  • path: Render the relative path for a given route and parameters. If there is no route, it returns the current path.

    {{ path('article_show', {'id': '3'}) }}
    Generates: /article/3

    path supports optional query parameters and a fragment identifier.

    {{ path('article_show', {'id': '3'}, {'foo': 'bar'}, 'fragment') }}
    Generates: /article/3?foo=bar#fragment

    By default the current route result is used where applicable. To disable this the reuse_result_params option can be set.

    {{ path('article_show', {}, {}, null, {'reuse_result_params': false}) }}
  • url: Render the absolute url for a given route and parameters. If there is no route, it returns the current url.

    {{ url('article_show', {'slug': 'article.slug'}) }}
    Generates: http://example.com/article/article.slug

    url also supports query parameters and a fragment identifier.

    {{ url('article_show', {'id': '3'}, {'foo': 'bar'}, 'fragment') }}
    Generates: http://example.com/article/3?foo=bar#fragment

    By default the current route result is used where applicable. To disable this the reuse_result_params option can be set.

    {{ url('article_show', {}, {}, null, {'reuse_result_params': false}) }}
  • absolute_url: Render the absolute url from a given path. If the path is empty, it returns the current url.

    {{ absolute_url('path/to/something') }}
    Generates: http://example.com/path/to/something
  • asset Render an (optionally versioned) asset url.

    {{ asset('path/to/asset/name.ext', version=3) }}
    Generates: path/to/asset/name.ext?v=3

    To get the absolute url for an asset:

    {{ absolute_url(asset('path/to/asset/name.ext', version=3)) }}
    Generates: http://example.com/path/to/asset/name.ext?v=3

Configuration

If you use the laminas-component-installer the factories are configured automatically for you when requiring this package with composer. Without the component installer, you need to include the ConfigProvider in your config/config.php. Optional configuration can be stored in config/autoload/templates.global.php.

'templates' => [
    'extension' => 'file extension used by templates; defaults to html.twig',
    'paths' => [
        // namespace / path pairs
        //
        // Numeric namespaces imply the default/main namespace. Paths may be
        // strings or arrays of string paths to associate with the namespace.
    ],
],
'twig' => [
    'cache_dir' => 'path to cached templates',
    'assets_url' => 'base URL for assets',
    'assets_version' => 'base version for assets',
    'extensions' => [
        // extension service names or instances
    ],
    'runtime_loaders' => [
        // runtime loaders names or instances   
    ],
    'globals' => [
        // Global variables passed to twig templates
        'ga_tracking' => 'UA-XXXXX-X'
    ],
    'timezone' => 'default timezone identifier, e.g.: America/New_York',
    'optimizations' => -1, // -1: Enable all (default), 0: disable optimizations
    'autoescape' => 'html', // Auto-escaping strategy [html|js|css|url|false]
    'auto_reload' => true, // Recompile the template whenever the source code changes
    'debug' => true, // When set to true, the generated templates have a toString() method
    'strict_variables' => true, // When set to true, twig throws an exception on invalid variables
],

Documentation

See the Mezzio Twig documentation.

mezzio-twigrenderer's People

Contributors

0nua avatar alexander-schranz avatar alucic avatar arueckauer avatar azjezz avatar bfolliot avatar boesing avatar caeret avatar dannym87 avatar edigu avatar elisdn avatar froschdesign avatar geerteltink avatar ghostwriter avatar grafikart avatar gsteel avatar harikt avatar koopzington avatar lucassabreu avatar michalbundyra avatar ncou avatar ocramius avatar powerkiki avatar renovate[bot] avatar samsonasik avatar tigerman55 avatar timdev avatar weierophinney avatar xerkus avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mezzio-twigrenderer's Issues

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Repository problems

These problems occurred while renovating this repository. View logs.

  • WARN: Use matchDepNames instead of matchPackageNames

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

composer
composer.json
  • php ~8.1.0 || ~8.2.0 || ~8.3.0
  • mezzio/mezzio-helpers ^5.0
  • mezzio/mezzio-router ^3.7
  • mezzio/mezzio-template ^2.0
  • psr/container ^1.0 || ^2.0
  • twig/twig ^3.4.3
  • laminas/laminas-coding-standard ~2.5.0
  • phpunit/phpunit ^10.5.2
  • psalm/plugin-phpunit ^0.19.0
  • vimeo/psalm ^5.17
github-actions
.github/workflows/continuous-integration.yml
.github/workflows/release-on-milestone-closed.yml

  • Check this box to trigger a request for Renovate to run again on this repository

PHP 8.0 support

Feature Request

Q A
New Feature yes

Summary

To be prepared for the december release of PHP 8.0, this repository has some additional TODOs to be tested against the new major version.

In order to make this repository compatible, one has to follow these steps:

  • Modify composer.json to provide support for PHP 8.0 by adding the constraint ~8.0.0
  • Modify composer.json to drop support for PHP less than 7.3
  • Modify composer.json to implement phpunit 9.3 which supports PHP 7.3+
  • Modify .travis.yml to ignore platform requirements when installing composer dependencies (simply add --ignore-platform-reqs to COMPOSER_ARGS env variable)
  • Modify .travis.yml to add PHP 8.0 to the matrix (NOTE: Do not allow failures as PHP 8.0 has a feature freeze since 2020-08-04!)
  • Modify source code in case there are incompatibilities with PHP 8.0

Ability to attach simple filters via configuration

Hello.

Few days ago I wanted to render a Money/Money instance in a twig template something like below:

<div> {{ customer.balance|money }} </div>

and needed to attach an additional custom filter into TwigEnvironment to achieve this goal. Altering the state of the environment somewhere else after it's creation bugged me a bit then decided to extend the whole factory which sounds also bad:

class MyTwigEnvironmentFactory extends ExpressiveTwigEnvironmentFactory
{
    public function __invoke(ContainerInterface $container): Environment
    {
        $environment = parent::__invoke($container);
        $environment->addFilter( ... );

        return $environment;

My actual filter implementation was so simple:

$filter = new TwigFilter('money', function (Money $money) {
    $currencies = ['EUR' => 2, 'USD' => 2];
    $formatter = new DecimalMoneyFormatter(new CurrencyList($currencies));

    return $formatter->format($money); // 
 })

Then I thought that I am literally doing a lot to achieve relatively small task and decided to introduce ability to attach simple filters using configuration.

This PR provides required functionality to attach custom filters into environment instance via configuration like following:

'twig' => [
    'filters' => [
         // user defined filters
         ['name' => 'greet', 'filter' => function($a) { return 'Hello ' . $a; } ],
         ['name' => 'mul', 'filter' => 'Math::multiply', 'options' => ['needs_context' => true] ],
         ['name' => 'money', 'filter' => ['MoneyHelper', 'format'] ],
         ['name' => 'uglify', 'filter' => \Lib\Twig\Filter\Uglify::class ],
     ],
],

I am open to hear opinions of other contributors to improve the implementation further.

Official docs for Twig Filters: https://twig.symfony.com/doc/2.x/advanced.html#filters


Originally posted by @edigu at zendframework/zend-expressive-twigrenderer#58

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.