{"id":46547,"date":"2017-02-28T12:16:25","date_gmt":"2017-02-28T06:46:25","guid":{"rendered":"http:\/\/www.tothenew.com\/blog\/?p=46547"},"modified":"2017-05-01T15:36:16","modified_gmt":"2017-05-01T10:06:16","slug":"overview-of-twig-extentions-in-drupal-8","status":"publish","type":"post","link":"https:\/\/www.tothenew.com\/blog\/overview-of-twig-extentions-in-drupal-8\/","title":{"rendered":"Overview of Twig Extentions in Drupal 8"},"content":{"rendered":"<p><a href=\"http:\/\/www.drupal.org\/docs\/8\"><span style=\"font-weight: 400;\">Drupal 8<\/span><\/a> introduces a great templating system &#8220;<span style=\"font-weight: 400;\"><strong>Twig<\/strong>&#8220;<\/span>\u00a0which is originating from Symfony, a PHP framework.<\/p>\n<p>This has brought about a big change in the Drupal community. Unlike Drupal 7, developers can&#8217;t use PHP functions directly\u00a0now on. Twig is a template framework and is a direct replacement for PHP template.<\/p>\n<p>Twig extension provides more flexibility to process almost anything inside twig. Twig extends in many ways such as\u00a0tags, filters, operators, global variables, and functions.<\/p>\n<p><strong>Outlined below are the advantages of using Twig Extensions<\/strong>:<\/p>\n<p><a title=\"Drupal 8 Development Services\" href=\"http:\/\/www.tothenew.com\/wcm\/drupal-development-consulting-services\">Drupal 8 <\/a>views can increase the challenge in the case\u00a0where you want to change, update or modify a value or need to process the content in the field. When you need to write a code often, try to reuse it rather than writing it from scratch every time.<\/p>\n<p><strong>Benefits of Twig Extensions<\/strong>:<\/p>\n<p>Creating twig extension helps to separate the compiled code and the code at runtime execution. Twig extension improves the experience with efficient coding techniques that involve lesser efforts and high flexibility.<\/p>\n<p>In the below example, we built an extension to render an image alt tag inside twig templates.<\/p>\n<p>To get started, we need to create a module for TwigExtension.<\/p>\n<p><strong>Creating your Twig Extension<\/strong><\/p>\n<p>To start with it\u00a0first, we need to create a module.<\/p>\n<p>1.) Create a new module inside: \/modules\/custom\/ directory inside your drupal project.<\/p>\n<p>2.) Our new module structure would look like this:<\/p>\n<p>[php]<br \/>\n|modules<br \/>\n|&#8211;custom<br \/>\n|&#8212;-demo_module<br \/>\n|&#8212;&#8212;demo_module.info.yml<br \/>\n|&#8212;&#8212;demo_module.services.yml<br \/>\n|&#8212;&#8212;src<br \/>\n|&#8212;&#8212;&#8211;TwigExtension.php<br \/>\n[\/php]<\/p>\n<p>3.) demo_module.info.yml contains<\/p>\n<p>[php]<br \/>\nname: demo_module<br \/>\ntype: module<br \/>\ndescription: \u2018Provides Twig Extension that process the Alt tag of any given image.\u2019<br \/>\ncore: 8.x<br \/>\nversion: 0.1.1<br \/>\n[\/php]<\/p>\n<p>Information provided inside module_name.info.yml is used to be displayed on admin module page.<\/p>\n<p>4.) Create a service file inside your module as \u2018module_name.services.yml\u2019<\/p>\n<p>[php]<br \/>\nservices:<br \/>\n  demo_module.twig.TwigExtension:<br \/>\n    class: Drupal\\demo_module\\TwigExtension<br \/>\n    tags:<br \/>\n      &#8211; {name: twig.extension}<br \/>\n[\/php]<\/p>\n<p>5.) The TwigExtension.php contains the following code<\/p>\n<p>[php]<br \/>\n&lt;?php<br \/>\nnamespace Drupal\\demo_module;<br \/>\nuse Drupal\\block\\Entity\\Block;<br \/>\nuse Drupal\\user\\Entity\\User;<br \/>\nuse Drupal\\node\\Entity\\Node;<\/p>\n<p>\/**<br \/>\n * Class DefaultService.<br \/>\n *<br \/>\n * @package Drupal\\demo_module<br \/>\n *\/<br \/>\nclass TwigExtension extends \\Twig_Extension {<\/p>\n<p>  \/**<br \/>\n   * {@inheritdoc}<br \/>\n   * This function must return the name of the extension. It must be unique.<br \/>\n   *\/<br \/>\n  public function getName() {<br \/>\n    return &#8216;block_display&#8217;;<br \/>\n  }<\/p>\n<p>  \/**<br \/>\n   * In this function we can declare the extension function.<br \/>\n   *\/<br \/>\n  public function getFunctions() {<br \/>\n    return array(<br \/>\n      new \\Twig_SimpleFunction(&#8216;getImageAlt&#8217;, array($this, &#8216;getImageAlt&#8217;), array(&#8216;is_safe&#8217; =&gt; array(&#8216;html&#8217;))),<br \/>\n    );<br \/>\n  }<br \/>\n  \/*<br \/>\n   * This function is used to return alt of an image<br \/>\n   * Set image title as alt.<br \/>\n   *\/<br \/>\n  public function getImageAlt($item) {<br \/>\n    $image_alt = NULL;<br \/>\n    if (method_exists($item, &#8216;getEntity&#8217;)) {<br \/>\n      $entity = $item-&gt;getEntity();<br \/>\n      $slide_image = $entity-&gt;get(&#8216;field_image&#8217;)-&gt;getValue();<br \/>\n      if ($slide_image) {<br \/>\n        if (isset($slide_image[0])) {<br \/>\n          $image = $slide_image[0];<br \/>\n          \/\/ set &quot;item title&quot; as alt.<br \/>\n          $item_value = $entity-&gt;get(&#8216;field_item_title&#8217;)-&gt;getValue();<br \/>\n          $image_alt = trim(strip_tags($item_value[0][&#8216;value&#8217;]));<br \/>\n          if(!empty($image_alt)){<br \/>\n            return $image_alt;<br \/>\n          }<br \/>\n          else {<br \/>\n            $image_alt = $image[&#8216;alt&#8217;];<br \/>\n            return $image_alt;<br \/>\n          }<br \/>\n        }<br \/>\n      }<br \/>\n    }<br \/>\n    return $image_alt;<br \/>\n  }<br \/>\n[\/php]<\/p>\n<p>6.) Now, enable your demo_module module.<br \/>\ndrush en demo_module -y<\/p>\n<p>7.) Clear the cache.<br \/>\ndrush cr<\/p>\n<p>8.) Applying Twig Extension to your twig template<br \/>\nYou can make a call to your TwigExtension directly inside template using \u201c{{ }}\u201d braces. These braces are used to render any content placed inside them.<\/p>\n<p>[php]<br \/>\n{% set imageAlt = getImageAlt(the_image) %}<br \/>\n&lt;img class=&quot;slide-content&quot; src=&quot;{{ image_style_url[key] }}&quot; alt=&quot;{{ imageAlt }}&quot; title=&quot;{{ the_image.title }}&quot;&gt;<br \/>\n[\/php]<\/p>\n<p>Moving further, set\u00a0the value from getImageAlt() function to a variable imageAlt inside node.html.twig placed in themes\/my_theme\/templates directory and then, render the variable imageAlt inside image alt tag.<\/p>\n<p>TwigExtension provides a great accessibility to the code which is often reused. With easy reusability of the code, it also saves a lot of time and efforts. Hope you will now be able to use Twig in Drupal 8.<\/p>\n<p>Watch out my blog for more updates on Drupal 8.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Drupal 8 introduces a great templating system &#8220;Twig&#8220;\u00a0which is originating from Symfony, a PHP framework. This has brought about a big change in the Drupal community. Unlike Drupal 7, developers can&#8217;t use PHP functions directly\u00a0now on. Twig is a template framework and is a direct replacement for PHP template. Twig extension provides more flexibility to [&hellip;]<\/p>\n","protected":false},"author":1037,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"iawp_total_views":16},"categories":[3602,1994,1],"tags":[258,4490,3601,4489,4356,4227,4456,4864],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts\/46547"}],"collection":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/users\/1037"}],"replies":[{"embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/comments?post=46547"}],"version-history":[{"count":0,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts\/46547\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/media?parent=46547"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/categories?post=46547"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/tags?post=46547"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}