Skip to content

Instantly share code, notes, and snippets.

@wesruv
Last active January 22, 2020 01:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wesruv/a154a5d341eef0dcc81ede74c241d872 to your computer and use it in GitHub Desktop.
Save wesruv/a154a5d341eef0dcc81ede74c241d872 to your computer and use it in GitHub Desktop.
D8 and D7 template file syntax

D8 and D7 template file syntax

Below are examples of basic structures you need in templating shown in Twig (Drupal 8) and PHPTemplate (Drupal 7).

Code Comments

{# My code comment, won't appear in the HTML #}
<?php // My code comment, won't appear in the HTML ?>

Print something

<p>
  Printing my variable: {{ my_variable }}
</p>
<p>
  Printing my variable: <?php print $my_variable; ?>
</p>

Result if my variable is set to hello world!:

<p>
  Printing my variable: hello world!
</p>

If statement

{% if (variable) %}
  <h1>My HTML</h1>
{% endif %}
<?php if ($variable): ?>
 <h1>My HTML</h1>
<?php endif; ?>

Setting and then Printing a variable in the middle of a string

{% set myContentId = 15 %}
<div id="node-{{ myContentId }}">
<?php $myContentId = 15; ?>
<div id="node-<?php print $myContentId; ?>">

Result: <div id="node-15">

Printing from the content array

{{ content.field_author }}
<?php print render($content['field_author']); ?>

Using a for statement to iterate over an array

{% for item in items %}
  <div{{ item.attributes }}>
    {{ item.content }}
  </div>
{% endfor %}
<?php foreach ($items as $delta => $item): ?>
  <div<?php print $item_attributes[$delta]; ?>>
    <?php print render($item); ?>
  </div>
<?php endforeach; ?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment