Convert a PHP template file into a Twig template

Final / Up to date -- Last peer review: 23 Sep 2013
In this lesson you will convert an existing PHPtemplate file and convert it to use the new Twig syntax

In this lesson you will practice converting a Drupal-7-style PHPTemplate file into a Drupal-8-style Twig template. Though all of these conversions have already been done in Drupal 8 core This exercise is a good one for getting yourself familiar with Twig.

  • You will need a Drupal 8 site.
  • A text editor.
  • A basic understanding of the Twig syntax.
  1. Copy a Drupal 7 PHPtemplate file
  2. Practice converting each piece of PHP code in the template into Twig syntax instead
    • print becomes {{
    • $vars becomes vars
    • foreach becomes for
  3. Play with common Twig syntax - documentation

Here is an example of the block template conversion:
Drupal 7 block.tpl.php

" class="<?php print $classes; ?>"<?php print $attributes; ?>>
<?php print render($title_prefix); ?>
<?php if ($block->subject): ?>
><?php print $block->subject ?>
<?php endif;?>
<?php print render($title_suffix); ?>
<?php print $content ?>

Drupal 8 block.html.twig

{{ title_prefix }}
{% if label %}
{{ label }}
{% endif %}
{{ title_suffix }}
{{ content }}

Lesson tags:


bryanbraun's picture

====== Create a New Template File ======

1. Create a new file named example.html

2. Copy the following PHPTemplate block template markup into the file:

// Example markup from block.tpl.php.
<div id="<?php print $block_html_id; ?>" class="<?php print $classes; ?>"<?php print $attributes; ?>>
<?php print render($title_prefix); ?>
<?php if ($block->subject): ?>
<h2<?php print $title_attributes; ?>><?php print $block->subject ?></h2>
<?php endif;?>
<?php print render($title_suffix); ?>
<div class="content"<?php print $content_attributes; ?>>
<?php print $content ?>

3. Using the <a href="">documentation</a> as a reference, convert the example template into a template with Twig syntax.
4. When you are done, compare your file to <a href="!modules!block!templates!block.htm... one in core</a>.
5. Did you get it all correct?

Update status: 
Final / Up to date

Thanks for documenting this.

I just would like to confirm a couple of things.

1. Should the file name 'example.html' be called 'example.html.twig'?
2. In your Twig example code, are lines 2 & 5 correct? e.g instead of {{ render ($title_prefix)}}it should be {{title_prefix}}. Sorry, I couldn't find a reference to the code above.

No, the example code from the first comment was not correct. I updated this lesson to add a correct code example.