Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Fluid Laravel Package

typo3fluid/fluid

TYPO3Fluid is a standalone PHP templating engine extracted from TYPO3 CMS. It provides secure, flexible templates with ViewHelpers, layouts, sections and partials, plus extensibility and caching, making it suitable for MVC apps and reusable component rendering.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup in Laravel

To integrate typo3fluid/fluid into a Laravel project, start by installing the package via Composer:

composer require typo3fluid/fluid

First Use Case: Rendering a Basic Template

Initialize Fluid in your Laravel application:

use Fluid\Fluid;
use Fluid\Core\Parser\TemplateParser;
use Fluid\Core\Compiler\TemplateCompiler;
use Fluid\Core\Rendering\RenderingContext;
use Fluid\Core\ViewHelper\ViewHelperResolver;

// Configure Fluid
$templatePath = resource_path('views/fluid/example.html');
$templateContent = file_get_contents($templatePath);

$parser = new TemplateParser();
$compiler = new TemplateCompiler();
$viewHelperResolver = new ViewHelperResolver();

// Create Fluid instance
$fluid = new Fluid($parser, $compiler, $viewHelperResolver);

// Set variables
$fluid->getVariableProvider()->add('name', 'John Doe');

// Render template
$renderingContext = new RenderingContext();
$output = $fluid->render($templateContent, $renderingContext);

echo $output;

Where to Look First

  • Documentation: Fluid Documentation (especially the ViewHelper Reference).
  • ViewHelper API: Explore built-in ViewHelpers like <f:for>, <f:if>, and <f:format.*>.
  • Template Files: Use .fluid.html extension (optional but recommended for Fluid 5+).

Implementation Patterns

Workflow: Templating in Laravel

  1. Template Structure: Store templates in resources/views/fluid/ with .fluid.html extension. Example: resources/views/fluid/email/welcome.fluid.html.

  2. Rendering Logic: Use a service class to encapsulate Fluid rendering logic:

    class FluidRenderer
    {
        protected $fluid;
    
        public function __construct()
        {
            $this->fluid = new Fluid(
                new TemplateParser(),
                new TemplateCompiler(),
                new ViewHelperResolver()
            );
        }
    
        public function render(string $templatePath, array $variables = []): string
        {
            $templateContent = file_get_contents($templatePath);
            $this->fluid->getVariableProvider()->addAll($variables);
            return $this->fluid->render($templateContent, new RenderingContext());
        }
    }
    
  3. Integration with Laravel Controllers: Inject FluidRenderer into controllers and use it to render templates dynamically.

    public function showWelcome(FluidRenderer $renderer)
    {
        $variables = [
            'user' => User::find(1),
            'products' => Product::all(),
        ];
        return response($renderer->render(
            resource_path('views/fluid/email/welcome.fluid.html'),
            $variables
        ));
    }
    

Common Patterns

  • Partial Templates: Use <f:render partial="partialName"> to modularize templates.
  • Sections: Define reusable sections with <f:section name="header"> and render them with <f:render section="header">.
  • ViewHelpers: Leverage built-in ViewHelpers (e.g., <f:format.currency>) or create custom ones.
  • Layouts: Use <f:layout> and <f:section> for consistent layouts.

Integration Tips

  • Caching: Enable template caching for performance:
    $compiler->setCacheDirectory(storage_path('framework/cache/fluid'));
    
  • Error Handling: Wrap rendering in try-catch to handle template errors gracefully.
  • Testing: Use FluidTestCase (if available) or mock Fluid for unit tests.

Gotchas and Tips

Pitfalls

  1. Variable Escaping: Fluid escapes variables by default for security. Use UnsafeHTML interface or <f:format.raw> to bypass escaping (use sparingly).

    $fluid->getVariableProvider()->add('html', new UnsafeHTML('<script>alert("XSS");</script>'));
    
  2. Template Path Resolution: Fluid 5+ uses a fallback chain for template names. Ensure your templates follow the naming conventions:

    • template.fluid.html (recommended)
    • template.html (legacy)
    • Template.fluid.html (case-sensitive fallback)
  3. Strict Argument Validation: Fluid 5 enforces strict argument validation for ViewHelpers. Ensure your custom ViewHelpers use proper type hints:

    public function render(): string { ... }
    
  4. CDATA Conflicts: Avoid { and } in inline CSS/JS. Use {{{ and }}} for Fluid syntax in <![CDATA[ ]]> sections.

Debugging Tips

  • Template Paths: Use --debug flag with the fluid warmup CLI command to verify template discovery:
    php artisan fluid:warmup --debug
    
  • Parser Errors: Check line numbers in error messages for exact template locations.
  • ViewHelper Arguments: Validate arguments against the ViewHelper’s metadata using:
    $viewHelper->getArguments();
    

Extension Points

  1. Custom ViewHelpers: Extend AbstractViewHelper to create reusable components:

    class MyCustomViewHelper extends AbstractViewHelper
    {
        public function render(): string
        {
            return 'Custom output';
        }
    }
    

    Register with the ViewHelperResolver.

  2. Template Parsing: Override TemplateParser to add custom syntax or preprocessors.

  3. Variable Providers: Implement VariableProviderInterface to inject dynamic data:

    $fluid->getVariableProvider()->addProvider(new MyCustomVariableProvider());
    
  4. Annotations API: Use annotations to document ViewHelper arguments and improve IDE support:

    /**
     * @param string $title The title of the section
     * @param int $priority The priority of the section (default: 0)
     */
    public function render(): string { ... }
    

Configuration Quirks

  • Cache Directories: Ensure the cache directory is writable and persistent across deployments.
  • Template Extensions: Avoid mixing .fluid.* and legacy extensions in the same project unless necessary.
  • CLI Commands: Use fluid warmup to precompile templates during deployment:
    php artisan fluid:warmup --path=resources/views/fluid --cache=storage/framework/cache/fluid
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
ecotone/kafka
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata