Installation Add the bundle via Composer:
composer require csanquer/twig-extra-bundle
Register the bundle in config/bundles.php:
return [
// ...
Csanquer\TwigExtraBundle\CsanquerTwigExtraBundle::class => ['all' => true],
];
First Use Case
Use the asset_manager Twig function to concatenate and render JS assets in a base layout:
{% block javascripts %}
{{ asset_manager([
'@YourBundle/Resources/public/js/app.js',
'@YourBundle/Resources/public/js/vendor.js'
]) }}
{% endblock %}
This outputs a single <script> tag with concatenated content in the order provided.
Asset Concatenation in Layouts
asset_manager call in a base template (e.g., base.html.twig) to ensure all JS assets are rendered once.{% block javascripts %}
{{ asset_manager([
'bundles/yourbundle/js/main.js',
'https://cdn.example.com/library.js'
]) }}
{% endblock %}
Conditional Asset Loading
if logic to load assets dynamically:
{% if app.user.isAdmin %}
{{ asset_manager(['@YourBundle/Resources/public/js/admin.js']) }}
{% endif %}
Integration with Webpack Encore
{{ encore_entry_link_tags('app') }}
{{ asset_manager(['@YourBundle/Resources/public/js/extra.js']) }}
Asset Grouping by Route
admin or frontend):
{% set adminAssets = ['@YourBundle/Resources/public/js/admin/*.js'] %}
{{ asset_manager(adminAssets) }}
asset() for local files and asset_manager for concatenation.Etag) to cache concatenated assets.dev environments for easier debugging:
{% if app.environment == 'dev' %}
{% for asset in assets %}
<script src="{{ asset(asset) }}"></script>
{% endfor %}
{% else %}
{{ asset_manager(assets) }}
{% endif %}
Asset Path Resolution
js/app.js) may fail if not rooted in public/.@YourBundle/Resources/public/js/app.js) or configure Twig’s paths in config/packages/twig.yaml.External CDN Assets
asset_manager may not handle CDN URLs (e.g., https://...) optimally, as they bypass Symfony’s asset pipeline.<script> tag.Caching Headaches
?v={{ filemtime('path/to/file.js') }}) or use Symfony’s AssetVersionStrategy.Twig Extension Conflicts
asset() from Symfony\Bridge\Twig\Extension\AssetExtension).{{ csanquer_asset_manager(...) }}) by overriding the Twig environment.php bin/console debug:twig | grep asset_manager
// In a custom Twig extension
public function getAssetPaths($assets) {
\Log::debug('Asset paths:', $assets);
return $assets;
}
Custom Asset Filters
// src/Twig/AppExtension.php
public function getFilters() {
return [
new \Twig\TwigFilter('minify_js', [$this, 'minifyJs']),
];
}
{{ asset_manager(assets | map('minify_js')) }}
Override AssetManager
AssetManager service to add logic (e.g., versioning):
# config/services.yaml
Csanquer\TwigExtraBundle\Twig\AssetManager:
arguments:
$version: '%kernel.cache_dir%/assets/version.txt'
Add Asset Types
AssetManager class:
// Override Csanquer\TwigExtraBundle\Twig\AssetManager
public function renderAssets(array $assets) {
foreach ($assets as $asset) {
if (strpos($asset, '.css') !== false) {
// Custom CSS logic
}
}
}
How can I help you explore Laravel packages today?