INTRODUCTION TO TWIG

&

Porting D7 to D8 THEMING 

Swastik Pareek

@swastik1608

Proud developer @qed42

Say Hi to {% Twig %}

Say Hi to {{ Twig }}

Say Hi to {# Twig #}

<?php 
/** 
 * Simple PHP template
 */
?>

<DIV>
    Hi! 
    <SPAN>
        <?php if ($user->gender === 'male') : ?>
           Mr.
        <?php elseif ($user->gender === 'female') : ?>
           Mrs.
        <?php endif; ?>
        <?php print $user->name['first'] ?> 
        <?php print $user->name['last'] ?>
    </SPAN>
    <UL>
        <?php foreach ($user->items as $item) : ?>
            <li> print $item ; </LI>
        <?php endforeach; ?>
    </UL>
</DIV>
{#
  # Simple Twig Template
#}

<div>
    Hi!
    <SPAN>
        {% if (user.gender == 'male') %}
           Mr.
        {% elseif (user.gender == 'female') %}
           Mrs.
        {% endif %}
        {{ user.name.first ~ user.name['last'] }}
    </SPAN>
    <UL>
        {% for item in user.items %}
            <li> {{ item }} </LI>
        {% endfor %}
    </UL>
</div>

Twig is Smarter

  • Filters
  • Tags
  • Functions
  • Extends
  • Tests

Inheritance in Twig

  • Includes
  • Use
  • Import
  • Extend
  • Embed

Other Superpowers of Twig

  • Powerful Debugging System
  • Helper Function and variables
  • Macros

Setting Up twig for your local Project

  1.  Clone Twig code
  2. Include Autloader.php
  3. Configure twig in a php server
  4. Add extension in php.ini 

Simple Hands On Example of twig coding

Strong Parts of D7

  • InBuilt Robust Debugging System
  • Built in classes rich markup
  • Modular Architecture with Theme Functions

How Things changed in D8

  • Theme Function is no more
  • YAML Structure in theming too
  • Change in way to load js and css
  • Template Engine Changed to TWIG
  • Core Templates moved in Theme folder

Power to you..

  • Cleaner Markup and flexibility
  • Power of TWIG - FASTER SECURE FLEXIBLE
  • Better Debugging
  • Simpler Architecture
  • Headless

Now you have a choice

And difference is this

 

The Difference..

Theme Functions - RIP

Theme Process - RIP

Use of rendered array in preprocess

And Other logic goes inside template

https://www.drupal.org/node/1843650

Rendering Array Finally promoted!

Drupal related Filters

  • without
<div {{attributes.class.addClass('superman')
|without('class')}}>
   
    Hello from your inner soul!

 </div>
  • safe_join
  • passthrough
  • clean_class

Add Your custom :)

Porting Theme to another Phase

 

Simple Steps

  • template.php -> THEMENAME.theme
  • Move all the logics of *.tpl.php to hook_preprocess()
  • THEMENAME.info ->  THEMENAME.info.yml
  • JS/CSS to - THEMENAME.libraries.yml.
  • and convert PHP Code to twig,
  • Adding Extensions if any.

Final Directory Structure

Change in flow -

Preprocess

 

to 

 

template files

Lets Code

Questions?

 

Porting D7 to D8 THEMING DCD 16

By Swastik Pareek

Porting D7 to D8 THEMING DCD 16

  • 617