PHP code example of christophersmith262 / twig_override

1. Go to this page and download the library: Download christophersmith262/twig_override library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

christophersmith262 / twig_override example snippets


use TwigOverride\Providers\ProviderInterface;

class AdvancedRewriteProvider implements ProviderInterface {

  private $users = [1 => 'Admin', 2 => 'Guest'];
  private $loader;
  
  public function __construct(\Twig_LoaderInterface $loader) {
    $this->loader = $loader;
  }
  
  /**
   * Overrides 'profile.twig' with 'profile--<uid>.twig' if the template exists.
   */
  public function rewriteTemplateName($template_name, array $with, array $_context, $only) {
    if ($template_name == 'profile.twig') {
      $uid = $this->getUid($with, $_context);
      $override = 'profile--' . $uid . '.twig';
      
      if ($this->loader->exists($override)) {
        return $override;
      }
    }
    
    return $template_name;
  }
  
  /**
   * Sets a 'user_name' parameter when 'user_id' is passed to a twig template.
   */
  public function preprocessTemplateArgs($template_name, array $with, array $_context, $only) {
    $uid = $this->getUid($with, $_context);
    
    if (!empty($this->users[$uid])) {
      $with['user_name'] = $this->users[$uid];
    }
    
    return $with;
  }
  
  protected getUid(array $with, array $_context) {
    if (!empty($with['user_id'])) {
      return $with['user_id'];
    elseif (!empty($_context['user_id'] && !$only) {
      return $_context['user_id'];
    }
    else {
      return NULL;
    }
  }
  
}