Download the PHP package kenny1911/twig-view without Composer
On this page you can find all versions of the php package kenny1911/twig-view. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download kenny1911/twig-view
More information about kenny1911/twig-view
Files in kenny1911/twig-view
Package twig-view
Short Description Type-safe Twig views with template validation and testing capabilities
License MIT
Informations about the package twig-view
Twig View
[English][Русский]
A package for typing Twig templates and verifying their correctness during testing.
The Problem
When using Twig templates, errors are often discovered only at runtime because static analyzers cannot effectively verify the correctness of data passed to templates. Common issues include:
- Passing non-existent variables to templates
- Lack of null checks
- Data type mismatches
The Solution
This package provides a system of typed views that explicitly define data structures for templates, along with tools for testing these views.
Installation
Usage
Describe view class, using View attribute
Creating a view class, that implements View interface
DEPRECATED!!! This method is deprecated. It's recommended to use the
Viewattribute instead.
Twig Template
hello.html.twig:
Rendering a View
Symfony Integration
The package includes an event subscriber for automatic integration with Symfony:
Now when a controller returns a View instance, it will automatically be rendered into a Response:
Testing
Use PHPUnit to verify the correctness of all views:
Testing Recommendations
-
Use the Real Twig Environment - Tests should use the same
Twig\Environmentinstance as in production -
Cover All Data Variants - The
iterateViewsmethod should return all possible data combinations for each template -
Test Edge Cases - Pay special attention to cases with
nullvalues and empty data - Enable strict_variables - This ensures strict variable checking in Twig
Creating a Custom TestCase
In practice, it's recommended to create a base class for testing views that uses the same templates as in production:
Then your view test would look like this:
Benefits
- Early Error Detection - Problems are identified during testing, not in production
- Typing - Explicit definition of data structures for each template
- Autocompletion - Better IDE understanding of data structures in templates
- Integration - Easy integration with Symfony and other frameworks
- Flexibility - Ability to test all possible template usage scenarios
Common Issues and Recommendations
- Always Check for
null- This is the most common cause of errors in Twig templates - Use strict_variables - Enable this option for strict variable checking
- Test All Data Variants - Ensure you cover all possible data states
- Use Real Templates - Tests should use the same templates as in production
License
MIT