Symfony 7: Twig
# Install
composer require symfony/twig-pack
# twig-pack is twig-bundle + twig/extra-bundle
# Check configuration
symfony console config:dump twig
# Show a list of twig functions, filters, globals and tests
symfony console debug:twig
# Check syntax errors
symfony console lint:twig
Coding standards
composer require --dev vincentlanglet/twig-cs-fixer
vendor/bin/twig-cs-fixer lint templates
vendor/bin/twig-cs-fixer lint templates --fix
Debug
{{ dump(variable }}
- PhpStorm: CTRL + ALT + SHIFT + L
- djLint
- "No files to check"
IDE
- PhpStorm: create from controller: ALT + Enter > Twig create template;
Naming
- directory: controller name or controller directory name if using sub-directories;
- file: method name;
Notes
- can detect getters (if object has getStuff method, in twig we can use
object.stuff
;
- prod: templates are cached; if editing templates in prod, cache has to be cleared manually;
TLDR;
- say:
{{
- do:
{%
- comment:
{#
Usage
- Controller:
render()
(extend AbstractController);
- Filters: use pipe;
- Loops:
{% for item in items %}...{% endfor %}
- Partials (prefix with '_''):
{{ include('_footer.html.twig') }}
;
- Render assets (
symfony/asset
): {{ asset('logical_path_from_debug') }}
;
- Render dynamic urls:
{{ path('route_name', { param: value }) }}
;
- Access php data from template (eg. same data in every page): create a Twig extension: Autoconfiguration
Themes
twig:
paths:
'templates/theme_tabler1': 'theme_tabler1'
'templates/theme_tabler2': 'theme_tabler2'
return $this->render('@theme_tabler1/development/tabler/combo.html.twig', []);