Twig is a powerful template engine for php. Drupal uses it heavily.

Lets look at some of the most useful methods and their syntax.

Setting some value to a variable

{% set product_title = "Some value" %}

Setting some Object value to a variable

If you want to assign value to a variable from some object.

{% set product_title = "#{paragraph.getTitle()}" %}

Strip html tags from rendered string

Say, I have a rendered string and I want to strip html tags from it. And, finally trim it. In this example, you will also see array usage.

{% set my_code = content.field1[0] | striptags | trim %}

Dyanamic assigning value to a variable based on condition

{% if content.field_usa_code[0] %}
    {% set usa_code = content.field_usa_code[0] | striptags|trim %}
{% endif %}

Concatenation of string with variables

{% set link_india = "{india_code}/?param1=#{india_code}" %}

Here, I’m using variables inside a string. Take a look at its alternative below.

Concatenation of string with variables

{% set link_india = "" ~ (india_code) ~ "/?param1=" ~ (india_code)" %}

Complex example using string concatenation with variable with functions

{% set amazon_link_usa = "" ~ (product_title | slice(0,50) | url_encode) ~ "&param2=#{usa_code}" %}

Here, I’m trimming the big string to 50 character max. Even if string is small, this code works. And its using another function url_encode to url encode a parameter to http query.