Created
January 24, 2019 16:25
Star
You must be signed in to star a gist
Custom Twig functions Drupal 8
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
name: Custom twig | |
type: module | |
description: Custom Twig functions | |
core: 8.x | |
package: Custom |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
services: | |
custom_twig.my_custom_twig_items: | |
class: Drupal\custom_twig\MyCustomTwigItems | |
tags: | |
- { name: twig.extension } |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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