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

Difane Twig Database Bundle Laravel Package

difane/difane-twig-database-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the bundle via Composer:

    composer require difane/difane-twig-database-bundle
    

    Enable it in config/bundles.php:

    return [
        // ...
        Difane\TwigDatabaseBundle\DifaneTwigDatabaseBundle::class => ['all' => true],
    ];
    
  2. Configuration Publish the default config:

    php bin/console difane:twig-database:install
    

    Update config/packages/difane_twig_database.yaml to define:

    • template_paths (database paths, e.g., ['app.templates']).
    • loader settings (e.g., cache: true).
  3. First Use Case Store a template in the database:

    php bin/console difane:twig-database:create app.templates/hello.html.twig
    

    Edit it via the CLI:

    php bin/console difane:twig-database:edit app.templates/hello.html.twig
    

    Use it in Twig:

    {% include 'app.templates/hello.html.twig' %}
    

Implementation Patterns

Workflows

  1. Hybrid Storage

    • Use filesystem for static templates (e.g., templates/base.html.twig).
    • Store dynamic templates (e.g., admin dashboards) in the database.
    • Configure paths in config/packages/difane_twig_database.yaml:
      difane_twig_database:
          template_paths:
              - '%kernel.project_dir%/templates'  # Filesystem
              - 'app.templates'                   # Database
      
  2. Template Management

    • Create/Edit: Use CLI commands for quick iterations:
      # Create a new template
      php bin/console difane:twig-database:create app.templates/newsletter.twig
      # Edit existing template
      php bin/console difane:twig-database:edit app.templates/newsletter.twig
      
    • Versioning: Leverage database transactions for atomic updates:
      // In a service
      $this->twigDatabaseManager->updateTemplate('app.templates/home.twig', $newContent);
      
  3. Integration with Twig

    • Extend Twig’s Loader to prioritize database templates:
      // config/packages/twig.yaml
      twig:
          loader:
              difane_twig_database:
                  paths: ['app.templates']
      
    • Use in templates:
      {% extends 'app.templates/base.html.twig' %}
      {% block content %}{% include 'app.templates/partials/header.twig' %}{% endblock %}
      
  4. Dynamic Template Rendering

    • Fetch templates by ID (useful for CMS-like systems):
      $template = $this->twigDatabaseManager->getTemplate('app.templates/article.twig');
      $html = $this->twig->render($template->getContent(), ['title' => 'Post']);
      

Best Practices

  • Naming Conventions: Use namespaced paths (e.g., admin.dashboard, user.profile) to avoid collisions.
  • Caching: Enable cache: true in config to avoid repeated DB queries.
  • Permissions: Restrict template edits to admin users via Symfony’s security system.

Gotchas and Tips

Pitfalls

  1. Loader Conflicts

    • Issue: If both filesystem and database paths use the same name (e.g., home.html.twig), the filesystem path takes precedence.
    • Fix: Use unique namespaces (e.g., db.templates/home.html.twig vs. fs.templates/home.html.twig).
  2. Case Sensitivity

    • Issue: Template paths are case-sensitive in the database (e.g., App.Templates/HELLO.twigapp.templates/hello.twig).
    • Fix: Standardize paths in lowercase or use a consistent naming convention.
  3. CLI Permissions

    • Issue: The difane:twig-database:edit command may fail if the database user lacks write permissions.
    • Fix: Grant INSERT, UPDATE, DELETE on the twig_template table:
      GRANT ALL PRIVILEGES ON twig_template TO your_db_user;
      
  4. Caching Quirks

    • Issue: Disabling cache: true causes performance degradation with frequent DB queries.
    • Fix: Cache template content in a service layer if dynamic updates are rare:
      $this->cache->get('template:app.templates/home.twig', function() {
          return $this->twigDatabaseManager->getTemplate('app.templates/home.twig')->getContent();
      });
      

Debugging

  1. Template Not Found

    • Debug: Check the twig_template table for the correct path. Run:
      php bin/console difane:twig-database:list
      
    • Fix: Ensure the path matches exactly (including case) and the template exists in the database.
  2. Loader Errors

    • Debug: Enable Twig debug mode in config/packages/dev/twig.yaml:
      twig:
          debug: true
          strict_variables: true
      
    • Fix: Verify the DifaneTwigDatabaseBundle is loaded before other Twig bundles.
  3. Migration Issues

    • Debug: If the twig_template table is missing, run:
      php bin/console doctrine:migrations:migrate
      
    • Fix: Ensure the bundle’s migrations are executed after installation.

Extension Points

  1. Custom Template Storage

    • Extend the Difane\TwigDatabaseBundle\Manager\TemplateManager to support additional storage backends (e.g., S3):
      class CustomTemplateManager extends TemplateManager {
          public function getTemplate($path) {
              // Add logic for S3 fallback
              return parent::getTemplate($path);
          }
      }
      
    • Override the service in config/services.yaml:
      services:
          Difane\TwigDatabaseBundle\Manager\TemplateManager:
              class: App\Service\CustomTemplateManager
      
  2. Event Listeners

    • Hook into template events (e.g., TemplateCreatedEvent) to log changes or notify users:
      // src/EventListener/TemplateListener.php
      class TemplateListener implements TemplateEvents {
          public function onTemplateCreated(TemplateCreatedEvent $event) {
              // Send email or log the change
          }
      }
      
    • Register the listener in config/services.yaml:
      services:
          App\EventListener\TemplateListener:
              tags:
                  - { name: 'kernel.event_listener', event: 'difane.twig_database.template.created' }
      
  3. Custom CLI Commands

    • Extend the bundle’s commands to add features like bulk imports:
      php bin/console app:twig-database:import /path/to/templates --namespace=app.templates
      
    • Create a custom command:
      class ImportTemplatesCommand extends ContainerAwareCommand {
          protected function execute(InputInterface $input, OutputInterface $output) {
              // Logic to import templates from filesystem to DB
          }
      }
      
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui