Twig Templates

This is a proposal to replace the .phtml templates used for earlier Magento extensions with a templating engine called Twig.

The move to a templating engine will help enforce a desirable isolation of the presentation layer from domain and business logic and data, which is a fundamental goal of Extension Model Improvements. Current .phtml templates allow inclusion of business logic and SQL queries within the presentation layer, which can create serious challenges for maintenance and upgrades. We see the following additional benefits from separating the presentation logic:

About Twig

We chose Twig because integrating it into Magento will give you the following features and benefits:

Learn more about Twig.

Twig vs. PHTML

Before and After

PHTML

<?php if ($this->canEmailToFriend()): ?>
  <p class="email-friend">
    <a href="<?php echo 
      $this->helper('Mage_Catalog_Helper_Product')
        ->getEmailToFriendUrl($_product) ?>">
      <?php echo $this->__('Email to a Friend') ?>
    </a>
  </p>
<?php endif; ?>

Twig

{% if product.canEmailToFriend %}
  <p class="email-friend">
    <a href="{{ links.emailToFriend }}">
    {{ 'Email to a Friend'|translate }}
    </a>
  </p>
{% endif %}

How to Get Started

This section describes how to begin using Twig in your existing Magento extension, and how to build your new Magento extension with Twig. Our reference implementation is in the Mage/Catalog extension.

Concrete Example

The Twig half of the above before and after comparison shows the contents of app/code/Mage/Catalog/view/frontend/product/view/options/type/date.twig. You might ask yourself how the various variables used in this template are made available to it. This section will try to show you how.

Warnings and Gotchas

Conclusion

We hope you can see some of the flexibility and power the use of Twig will bring to your development efforts on Magento. Our aim is to make development fun for you again by separating front-end design from back-end work and ensuring that you are looking at clean, easy-to-read, and easy-to-debug code.

Please leave any comments/feedback about the use of Twig in Magento here