Skip to content

Instantly share code, notes, and snippets.

@mariacha
Created January 24, 2019 16:25
  • Star 1 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save mariacha/5f7834b28536b336031827946f7e3c90 to your computer and use it in GitHub Desktop.
Custom Twig functions Drupal 8
name: Custom twig
type: module
description: Custom Twig functions
core: 8.x
package: Custom
services:
custom_twig.my_custom_twig_items:
class: Drupal\custom_twig\MyCustomTwigItems
tags:
- { name: twig.extension }
<?php
namespace Drupal\custom_twig;
/**
* Class MyCustomTwigItems.
*/
class MyCustomTwigItems extends \Twig_Extension {
/**
* {@inheritdoc}
*/
public function getFilters() {
return [
new \Twig_SimpleFilter('field_respectful_label', [$this, 'getRespectfulFieldLabel']),
];
}
/**
* Twig filter callback: Only return a field's label if not hidden.
*
* @param array $build
* Render array of a field.
*
* @return string
* The label of a field. If $build is not a render array of a field, NULL is
* returned.
*/
public function getRespectfulFieldLabel(array $build) {
// Only proceed if this is a renderable field array.
if (isset($build['#theme']) && $build['#theme'] == 'field') {
// Find out the label value.
$disrespectful_label = isset($build['#title']) ? $build['#title'] : NULL;
// Find out the visibility status of the label.
$display_label = isset($build['#label_display']) ? ($build['#label_display'] != 'hidden') : FALSE;
return ($disrespectful_label && $display_label) ? $disrespectful_label : NULL;
}
return NULL;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment