Is there a way to use .tpl.php templates instead of Twig templates in Drupal 8, or is there a way to write PHP in a Twig file instead of that Twig language?
I am a beginner for Drupal 8, but I have worked with Drupal 7.
Is there a way to use .tpl.php templates instead of Twig templates in Drupal 8, or is there a way to write PHP in a Twig file instead of that Twig language?
I am a beginner for Drupal 8, but I have worked with Drupal 7.
You don't need to write PHP in twig files. Twig is fairly expressive to the degree in which you need to template, for everything else, it should go into the .theme file, theme hook, and/or preprocess function.
There is virtually no reason to have PHP code in a template.
Spend a week with Twig and you won't go back.
Example:
<?php if ($page['content']): ?>
<?php print render($page['content']); ?>
<?php endif; ?>
vs:
{% if page.content %}
{{ page.content }}
{% endif %}
Much more readable.
I'll expand with a more advanced example.
Lets say you have list of things you want to output, but every 7 items, you want to make a new unordered list. The end goal is the CSS inlines these lists, think of a superfish menu where menu links are ordered top to bottom, then left to right.
<div class="global-top__submenu">
{% for chunk in items|batch(7) %}
<ul class="global-top__submenu-col">
{% for item in chunk %}
<li>
{{ link(item.title, item.url) }}
</li>
{% endfor %}
</ul>
{% endfor %}
</div>
Where items
is passed to the template. This small example will output a UL with 7 items until there is nothing left to print.
I have yet to run into an instance where I cannot accomplish something with Twig, or, because it's Twig.
Give it a shot and dive in, forget phptemplate.
To use custom PHP and display the result in a template, you must go through preprocessing functions (like hook_preprocess_node()
) to override the display or add new variables to display in your template. You can create a custom module or use the MYTEHEME.theme file of your current theme to call preprocessing function.
If before you used a lot of PHP code in TPL files, it's bad practice because the files are used to display the data not to make hard particular/specific treatments inside.