3.3 Demonstrate ability to use Twig syntax
Review Twig syntax. Review Twig manipulation.
Twig is now the default template engine for D8. In Drupal 7 the default was PHP templates.
3 syntax twig changes to note
{{ Say Something }}
{{ Say Something }}
Print Syntax: {{ }}
Use the curly braces to print out values of variables. This is similar to the print render()
function from Drupal 7.
As of Drupal 8, page titles are blocks by default. Therefore, they have their own twig template: /core/themes/classy/templates/content/page-title.html.twig
At the top of classy's page-title.html.twig
docs there are variables available by default. The variable {{ title }}
will print the entity's title field value. "The page title, for use in the actual content." For example:
{% Do Something %}
{% Do Something %}
The `
syntax is for code syntax. From the above
/core/themes/classy/templates/content/page-title.html.twig example.The
` uses the if statement to only print a page title if there is a value.
The `
` can also be used to extend templates.
For example, extend page-title.html.twig would use the original twig template as its base.
{
#Comment on Something# }
{
#Comment on Something# }
Use the {# #}
syntax for comments and documentation.
Why Twig?
Changing the template engine to use twig helps separate the concerns of functional business logic and the presentation markup. Twig auto-escapes and sanitizes HTML to prevent XRSF attacks. Twig Syntax replaces the use of print()
and render()
Twig Manipulation
There are filters you can use to manipulate variables. Separate filters by from the variable with the |
operation. Chaining filters is also possible.
For example, if you want to join several strings together you can use the safe_join
filter. For Example"
This will print the items value concatenated together with a comma separating each item. Although filters and twig come from the Symfony integration, there are Drupal specific filters which are located at Drupal specific filters are declared in Drupal\Core\Template\TwigExtension::getFilters()
BLT can validate twig errors with
blt validate:twig
Other Resources
Last updated