Skip to content

Instantly share code, notes, and snippets.

@NodarDavituri
Last active July 20, 2018 08:16
Show Gist options
  • Save NodarDavituri/42349da266d15f21bd026e2ec4d87d92 to your computer and use it in GitHub Desktop.
Save NodarDavituri/42349da266d15f21bd026e2ec4d87d92 to your computer and use it in GitHub Desktop.
Custom Twig Extension Sample for Drupal 8
services:
acme_twig_helpers:
class: Drupal\acme_twig_helpers\TwigExtension
tags:
- { name: twig.extension }
<?php
/* acme_twig_helpers/src/TwigExtension.php */
namespace Drupal\acme_twig_helpers;
use Drupal\Component\Utility\Html;
use Drupal\taxonomy\Entity\Term;
use Twig_Extension;
use Twig_SimpleFunction;
/**
* Class TwigExtension.
*
* @package Drupal\acme_twig_helpers
*/
class TwigExtension extends Twig_Extension
{
/**
* {@inheritdoc}
*/
public function getName(){
return 'acme_twig_helpers';
}
/**
* {@inheritdoc}
*/
public function getFilters(){
return [
new \Twig_SimpleFilter('path_to_class', [$this, 'getPathToClass']),
];
}
/**
* {@inheritdoc}
*/
public function getFunctions(){
return [
new Twig_SimpleFunction('term_name', [$this, 'getTermName']),
];
}
/*
* Converts '/path/like/this' to CSS class name.
* Usefull in menu templates.
*
* Example: {{ '/about/contact' | path_to_class }}
* Outputs: about-contact
*/
public function getPathToClass($path) {
$path = array_filter(explode('/', $path));
$path = array_values($path);
$path = implode('-', $path);
return Html::getClass($path);
}
/*
* Returns name of a term given its TID.
* Might be useful in Views to override title
* when using term contextual filters.
*
* Example: term_name(457)
* Outputs: [name of the term 457]
*/
public function getTermName($tid){
// Normalize if $tid is a Markup
$tid = "".$tid;
$term = Term::load($tid);
if($term) {
return $term->getName();
}
return '';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment