{"id":16674815,"url":"https://github.com/odan/twig-assets","last_synced_at":"2025-04-09T10:07:53.802Z","repository":{"id":46261399,"uuid":"112045064","full_name":"odan/twig-assets","owner":"odan","description":"A Twig Assets Extension","archived":false,"fork":false,"pushed_at":"2024-11-12T04:24:19.000Z","size":192,"stargazers_count":22,"open_issues_count":1,"forks_count":6,"subscribers_count":3,"default_branch":"master","last_synced_at":"2025-04-02T08:11:13.244Z","etag":null,"topics":["asset-cache","assets","php","slim-framework","twig","twig-assets","twig-extension"],"latest_commit_sha":null,"homepage":"","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/odan.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2017-11-26T00:42:50.000Z","updated_at":"2024-10-24T16:27:35.000Z","dependencies_parsed_at":"2024-06-18T18:31:09.858Z","dependency_job_id":"dca8e1c7-ed05-434b-9008-dbe6b4eaf8b5","html_url":"https://github.com/odan/twig-assets","commit_stats":{"total_commits":152,"total_committers":7,"mean_commits":"21.714285714285715","dds":"0.11842105263157898","last_synced_commit":"f04ed882683415332797bfaa2431f11275028304"},"previous_names":[],"tags_count":22,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/odan%2Ftwig-assets","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/odan%2Ftwig-assets/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/odan%2Ftwig-assets/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/odan%2Ftwig-assets/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/odan","download_url":"https://codeload.github.com/odan/twig-assets/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248018060,"owners_count":21034048,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["asset-cache","assets","php","slim-framework","twig","twig-assets","twig-extension"],"created_at":"2024-10-12T12:44:28.130Z","updated_at":"2025-04-09T10:07:53.762Z","avatar_url":"https://github.com/odan.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Twig Assets Extension\n\nCaching and compression for Twig assets (JavaScript and CSS), inspired by [Symfony Web Assets](https://symfony.com/doc/3.0/best_practices/web-assets.html).\n\n[![Latest Version on Packagist](https://img.shields.io/github/release/odan/twig-assets.svg)](https://github.com/odan/twig-assets/releases)\n[![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg)](LICENSE.md)\n[![Build Status](https://github.com/odan/twig-assets/workflows/build/badge.svg)](https://github.com/odan/twig-assets/actions)\n[![Code Coverage](https://scrutinizer-ci.com/g/odan/twig-assets/badges/coverage.png?b=master)](https://scrutinizer-ci.com/g/odan/twig-assets/code-structure)\n[![Quality Score](https://scrutinizer-ci.com/g/odan/twig-assets/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/odan/twig-assets/?branch=master)\n[![Total Downloads](https://img.shields.io/packagist/dt/odan/twig-assets.svg)](https://packagist.org/packages/odan/twig-assets/stats)\n\n\n## Installation\n\n```\ncomposer require odan/twig-assets\n```\n\n## Requirements\n\n* PHP 8.2, 8.3\n* Twig 3\n\n## Configuration\n\n```php\n$options = [\n    // Public assets cache directory\n    'path' =\u003e '/var/www/example.com/htdocs/public/assets/cache',\n    \n    // Public cache directory permissions (octal)\n    // You need to prefix mode with a zero (0)\n    // Use -1 to disable chmod\n    'path_chmod' =\u003e 0750,\n    \n    // The public url base path\n    'url_base_path' =\u003e 'assets/cache/',\n    \n    // Internal cache settings\n    //\n    // The main cache directory\n    // Use '' (empty string) to disable the internal cache\n    'cache_path' =\u003e '/var/www/example.com/htdocs/temp',\n    \n    // Used as the subdirectory of the cache_path directory, \n    // where cache items will be stored\n    'cache_name' =\u003e 'assets-cache',\n    \n    // The lifetime (in seconds) for cache items\n    // With a value 0 causing items to be stored indefinitely\n    'cache_lifetime' =\u003e 0,\n    \n    // Enable JavaScript and CSS compression\n    // 1 = on, 0 = off\n    'minify' =\u003e 1\n];\n```\n\n## Integration\n\n### Register the Twig Extension\n\n```php\n$loader = new \\Twig\\Loader\\FilesystemLoader('/path/to/templates');\n$twig = new \\Twig\\Environment($loader, array(\n    'cache' =\u003e '/path/to/compilation_cache',\n));\n\n$twig-\u003eaddExtension(new \\Odan\\Twig\\TwigAssetsExtension($twig, $options));\n```\n\n### Slim 4 Framework\n\nRequirements\n\n* [Slim Framework Twig View](https://github.com/slimphp/Twig-View/tree/3.x)\n\nRun:\n\n```\ncomposer require slim/twig-view\n```\n\nAdd these settings:\n\n```php\n// Twig settings\n$settings['twig'] = [\n    'path' =\u003e __DIR__ . '/../templates',\n    // Should be set to true in production\n    'cache_enabled' =\u003e false,\n    'cache_path' =\u003e __DIR__ . '/../tmp/twig-cache',\n];\n\n// Twig assets cache\n$settings['assets'] = [\n    // Public assets cache directory\n    'path' =\u003e __DIR__ . '/../public/cache',\n    // Public url base path\n    'url_base_path' =\u003e 'cache/',\n    // Internal cache directory for the assets\n    'cache_path' =\u003e __DIR__ . '/tmp/twig-assets',\n    'cache_name' =\u003e 'assets-cache',\n    //  Should be set to 1 (enabled) in production\n    'minify' =\u003e 1,\n];\n```\n\nAdd a DI container definition.\n\n*This examples uses [PHP-DI](https://github.com/slimphp/Twig-View/tree/3.x#usage)*\n\n```php\n\u003c?php\n\nuse Odan\\Twig\\TwigAssetsExtension;\nuse Psr\\Container\\ContainerInterface;\nuse Slim\\App;\nuse Slim\\Factory\\AppFactory;\nuse Slim\\Views\\Twig;\nuse Twig\\Loader\\FilesystemLoader;\n\nreturn [\n    // ...\n\n    Twig::class =\u003e function (ContainerInterface $container) {\n        $settings = $container-\u003eget('settings');\n        $twigSettings = $settings['twig'];\n\n        $twig = Twig::create($twigSettings['path'], [\n            'cache' =\u003e $twigSettings['cache_enabled'] ? $twigSettings['cache_path'] : false,\n        ]);\n\n        $loader = $twig-\u003egetLoader();\n        if ($loader instanceof FilesystemLoader) {\n            $loader-\u003eaddPath($settings['public'], 'public');\n        }\n\n        $environment = $twig-\u003egetEnvironment();\n\n        // Add Twig extensions\n        $twig-\u003eaddExtension(new TwigAssetsExtension($environment, (array)$settings['assets']));\n\n        return $twig;\n    },\n\n];\n```\n\nAdd the `TwigMiddleware`. In this case we pass the full\nclass name `Twig::class` as the second parameter, because the\ncontainer entry is defined with the same name.\n\n```php\nuse Slim\\Views\\Twig;\nuse Slim\\Views\\TwigMiddleware;\n\n// ...\n\n$app-\u003eadd(TwigMiddleware::createFromContainer($app, Twig::class));\n```\n\nAdd a route, e.g. in `confg/routes.php`:\n\n```php\n$app-\u003eget('/', \\App\\Action\\Home\\HomeAction::class)-\u003esetName('root');\n```\n\nCreate a action class, e.g. `src/Action/HomeAction.php`:\n\n```php\n\u003c?php\n\nnamespace App\\Action\\Home;\n\nuse Psr\\Http\\Message\\ResponseInterface;\nuse Psr\\Http\\Message\\ServerRequestInterface;\nuse Slim\\Views\\Twig;\n\n/**\n * Action.\n */\nfinal class HomeAction\n{\n    /**\n     * @var Twig\n     */\n    private $twig;\n\n    /**\n     * The constructor.\n     *\n     * @param Twig $twig The twig engine\n     */\n    public function __construct(Twig $twig)\n    {\n        $this-\u003etwig = $twig;\n    }\n\n    public function __invoke(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface\n    {\n        return $this-\u003etwig-\u003erender($response, 'home/home.twig');\n    }\n}\n```\n\nThe (pseudo) content of `templates/home/home.twig`:\n\n```twig\n\u003chtml\u003e\n    \u003chead\u003e\n        {{ assets({files: ['home/index.css']}) }}\n    \u003c/head\u003e\n    \u003cbody\u003e\n        {{ assets({files: ['home/index.js']}) }}\n    \u003c/body\u003e\n\u003c/html\u003e\n```\n\nRead more: [Usage](#usage)\n\n### Slim 3 Framework\n\nRequirements\n\n* [Slim Framework Twig View](https://github.com/slimphp/Twig-View)\n\nIn your `dependencies.php` or wherever you add your Service Factories:\n\n```php\n$container[\\Slim\\Views\\Twig::class] = function (Container $container) {\n    $settings = $container-\u003eget('settings');\n    $viewPath = $settings['twig']['path'];\n\n    $twig = new \\Slim\\Views\\Twig($viewPath, [\n        'cache' =\u003e $settings['twig']['cache_enabled'] ? $settings['twig']['cache_path']: false\n    ]);\n\n    /** @var \\Twig\\Loader\\FilesystemLoader $loader */\n    $loader = $twig-\u003egetLoader();\n    $loader-\u003eaddPath($settings['public'], 'public');\n\n    // Instantiate and add Slim specific extension\n    $basePath = rtrim(str_ireplace('index.php', '', $container-\u003eget('request')-\u003egetUri()-\u003egetBasePath()), '/');\n    $twig-\u003eaddExtension(new \\Slim\\Views\\TwigExtension($container-\u003eget('router'), $basePath));\n    \n    // Add the Assets extension to Twig\n    $twig-\u003eaddExtension(new \\Odan\\Twig\\TwigAssetsExtension($twig-\u003egetEnvironment(), $settings['assets']));\n\n    return $twig;\n};\n```\n\n## Usage\n\n### Custom template functions\n\nThis Twig extension exposes a custom `assets()` function to your Twig templates. You can use this function to generate complete URLs to any Slim application assets.\n\n#### Parameters\n\nName | Type | Default | Required | Description\n--- | --- | --- | --- | ---\nfiles | array | [] | yes | All assets to be delivered to the browser. [Namespaced Twig Paths](http://symfony.com/doc/current/templating/namespaced_paths.html) (`@mypath/`) are also supported.\ninline | bool | false | no | Defines whether the browser downloads the assets inline or via URL.\nminify | bool | true | no | Specifies whether JS/CSS compression is enabled or disabled.\nname | string | file | no | Defines the output file name within the URL.\nnonce | string | | no | The CSP (content security policy) nonce (per request)\n\n### Template\n\n#### Output cached and minified CSS content\n\n```twig\n{{ assets({files: ['Login/login.css']}) }}\n```\n\nOutput cached and minified CSS content inline:\n\n```twig\n{{ assets({files: ['Login/login.css'], inline: true}) }}\n```\n\nOutput multiple CSS assets into a single .css file:\n\n```twig\n{{ assets({files: [\n    '@public/css/default.css',\n    '@public/css/print.css',\n    'User/user-edit.css'\n    ], name: 'layout.css'})\n}}\n```\n\n#### Output cached and minified JavaScript content\n\n```twig\n{{ assets({files: ['Login/login.js']}) }}\n```\n\nOutput multiple JavaScript assets into a single .js file:\n\n```twig\n{{ assets({files: [\n    '@public/js/my-js-lib.js',\n    '@public/js/notify.js',\n    'Layout/app.js'\n    ], name: 'layout.js'})\n}}\n```\n\n#### Output page specific assets\n\nContent of file: `layout.twig`\n\n```twig\n\u003chtml\u003e\n    \u003chead\u003e\n        {% block assets %}{% endblock %}\n    \u003c/head\u003e\n    \u003cbody\u003e\n        {% block content %}{% endblock %}\n    \u003c/body\u003e\n\u003c/html\u003e\n```\n\nContent of `home.twig`:\n\n```twig\n{% extends \"Layout/layout.twig\" %}\n\n{% block assets %}\n    {{ assets({files: ['Home/home.js'], name: 'home.js'}) }}\n    {{ assets({files: ['Home/home.css'], name: 'home.css'}) }}\n{% endblock %}\n\n{% block content %}\n    \u003cdiv id=\"content\" class=\"container\"\u003e\u003c/div\u003e\n{% endblock %}\n```\n\n#### Add custom attributes to the html element\n\n**WARNING:** you can override ANY attribute including i.e. `href`. Be careful here as it can cause unwanted results.\n\n```twig\n{{ assets({files: [\n    '@public/css/default.css',\n    '@public/css/print.css',\n    'User/user-edit.css'\n    ], attributes: {\n    rel: 'preload',\n    as: 'style',\n    onload: 'this.onload=null;this.rel=\\'stylesheet\\''\n    }, name: 'layout.css'})\n}}\n```\n\n\n## Configure a base path\n\nYou should inform the browser where to find the web assets with a `base href` in your layout template. \n\n### Slim Twig example:\n\n```twig\n\u003c!DOCTYPE html\u003e\n\u003chtml\u003e\n\u003chead\u003e\n    \u003cmeta charset=\"utf-8\"\u003e\n    \u003c!-- other stuff --\u003e\n    \u003cbase href=\"{{ base_path() }}/\"/\u003e\n    \u003c!-- other stuff --\u003e\n```\n\n## Clearing the cache\n\n### Clearing the internal cache\n\n```php\nuse Odan\\Twig\\TwigAssetsCache;\n\n$settings = $container-\u003eget('settings');\n\n// Internal twig cache path e.g. tmp/twig-cache\n$twigCachePath = $settings['twig']['cache_path']; \n\n$internalCache = new TwigAssetsCache($twigCachePath);\n$internalCache-\u003eclearCache();\n```\n\n### Clearing the public cache\n\n```php\nuse Odan\\Twig\\TwigAssetsCache;\n\n$settings = $container-\u003eget('settings');\n\n// Public assets cache directory e.g. 'public/cache' or 'public/assets'\n$publicAssetsCachePath = $settings['assets']['path'];\n\n$internalCache = new TwigAssetsCache($publicAssetsCachePath);\n$internalCache-\u003eclearCache();\n```\n\n## Testing\n\n```bash\ncomposer test\n```\n\n## Similar libraries\n\n* [Webpack](https://webpack.js.org/)\n* [Compiling Assets with Webpack](https://odan.github.io/2019/09/21/slim4-compiling-assets-with-webpack.html)\n\n## License\n\nThe MIT License (MIT). Please see [License File](LICENSE) for more information.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fodan%2Ftwig-assets","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fodan%2Ftwig-assets","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fodan%2Ftwig-assets/lists"}