What is twig?
Twig is the new theming engine in Drupal 8! PHPTemplate was removed due to no longer being actively maintained and with several security flaws. But instead of dreading the change to how themes work, developers should be excited about the change to Twig and what they can do with it. In this post, we'll talk about creating basic themes with Twig and the way that they work.
Development environment
Comments in twig:
To comment out one or more lines of code (or part of a line) use the the {# #} syntax.
{# Comment single line #}
{# This will be a
multi-line
comment.
#}
The loop variable
Inside of a for
loop block you can access some special variables:
Variable | Description |
---|---|
loop.index | The current iteration of the loop. (1 indexed) |
loop.index0 | The current iteration of the loop. (0 indexed) |
loop.revindex | The number of iterations from the end of the loop (1 indexed) |
loop.revindex0 | The number of iterations from the end of the loop (0 indexed) |
loop.first | True if first iteration |
loop.last | True if last iteration |
loop.length | The number of items in the sequence |
loop.parent | The parent context |
Example:
{% if loop.index%2 == 0 %}
<div class="clearfix visible-xs"></div>
{% endif %}
Twig Filters: Bộ lọc
Twig filters give us the ability to modify variables on twig template.
{% set salutevariable = "Hello Friend" %}"
If we output the variable {{ salutevariable }} is going to show: Hello Friend
If we want to make the variable lowercase, we use a filter.
{{ salutevariable | lower }}
the "|" indicates that we are going to use a filter in our case "lower", so the value "Hello Friend" is going to be parsed by the filter lower.
The output will be: hello friend
Remove html tags in twig
Set a variable first and striptags will work.
{% set sub_title %}
{{ content.field_sub_title }}
{% endset %}
{{ sub_title |striptags }}
Tips in Drupal theme
Get site name:
Add this to the YOUR_THEME.theme file:
function YOUR_THEME_preprocess_page(&$variables) {
$variables['site_name'] = \Drupal::config('system.site')->get('name');
}
And then this in your page--front.html.twig template: {{ site_name }}
Get theme path
Add this to the YOUR_THEME.theme file:
function YOUR_THEME_preprocess_page(&$variables) {
$variables['theme_path'] = base_path() . $variables['directory'];
}
And then this in your page--front.html.twig template: {{ theme_path}}
Get raw value
You can use Twig Field Value module in this case. After install this module You will get access to partial data from field render arrays.
For ex.
{{ content.field_name|field_value }}
content.field_image|field_target_entity.uri.value