Skip to main content

Featured

Build docker image from multiple build contexts

Build docker image from multiple build contexts Building a docker image requires specifying a source of truth to include in the image from a local directory or a remote git repository. In the previous version, the docker BuildKit allows users to specify the build context from a single source of truth only. However, the engineers may need to have the context from different locations based on the type of files. For instance, icons, images or other resources that are not included in the same package, including the resource from other docker images. Fortunately, the Docker Buildx toolkit supports multiple build context flag for Docker 1.4. Let's learn how to use this new feature. The following list is a shortcut for jumping into a specific topic handy. What version of Docker is this tutorial targeting? How to specify the version of Dockerfile frontend? Ho

[Tutorial] How to use variables in Twig

The tools used in this tutorial are as following:
|Spec        | Version      |
|:------------:|--------------|
|OS          | MacOS 10.14.3|
|PHP         | >= 7.0    |
|Twig        | 2.x          |

Note. This post is written in Markdown language which has not been supported in Blogger for mobile browser yet . Please read this article by a desktop computer for a better experience.

# Introduction
Like other languages, Twig has variables and expressions for developers and designers to implement user interface template. In this section, let's see how to use variables in Twig.


# How to do
It's simple to write a variable in Twig as in PHP. 
```twig
{# if name is kitty by setting #}
  name
```


However, it will be printed as plain text in the webpage if we write a variable as above. 
```
name
```


In order to print the value of the variable, a pair of curly braces have to be used to enclose the variable.
```twig
  {# if name is kitty by setting #}
  {{ name }}
```

Then Twig template engine will print it on the webpage. ``` kitty ```
The variables are also able to be manipulated in the control structure: ```twig {% set name = 'kitty' %} {% if name is not empty %} {% set greeting = "Hello " ~ name %} {% else %} {% set greeting = "Hellow Anonymous" %} {% endif %} {{ greeting }} ```
The result is: ``` Hello kitty ```
If the variable is an object, the attributes(properties) of a variable can be accessed by a dot symbol(.). ```twig house.door ```
The attributes of a variable are also able to be accessed by "subscript" syntax. However, it doesn't work for the attributes which have special characters, such as '-', in the name. ```twig house['door'] ```
In order to let designer and developer access attributes which have special characters in the name, Twig provides `attribute()` for designer and developer to access attributes. ```twig attribute(house, 'data-door') ```
A null will be returned if a variable or attribute does not exist when the `strict_variables` option is set to false, otherwise, Twig will throw an error.
The convenient thing is multiple variables can be assigned values at the same time in one line: ```twig {% set door, room = 4, 2 %} ``` It is equivalent to: ```twig {% set door = 4 %} {% set room = 2 %} ``` # Practice Let's do some practice. The JSON object for practice is as follows: ```json { "houses":[ { "name": "1 storey house", "door": 4, "window": 4, "room": 4 }, { "name": "2 storey house", "door": 4, "window": 4, "room": 2 } ] } ```
Let's print the details of houses: ```twig {% for house in houses %} {{ house.door }} doors in {{ house.name }} {% endfor %} ```
The result will be: ``` 4 doors in 1 storey house 4 doors in 2 storey house ``` # Setting Variables The variables can be set a value, such as string, integer, floating number, array, and key-value pairs, by Control Structure in a variant way. ## Set a string to a variable ```twig {% set var = 'this is a string' %} {# Tests the result #} {{ var }} ``` The result will be ``` this is a string ```
## Set an integer to a variable ```twig {% set var = 15 %} {# Tests the result #} {{ var }} ```
The result will be ``` 15 ```
## Set a floating number to a variable ```twig {% set var = 12.33456 %} {# Tests the result #} {{ var }} ```
The result will be ``` 12.33456 ```
## Set a string array to a variable ```twig {% set string_array = ['one', 'two', 'three', 'four'] %}
{# Tests the result #} {% for str in string_array %} {{ str }} {% endfor %} ```
The result will be ``` one two three four ```
## Set an integer array to a variable ```twig {% set integer_array = [1, 2, 3, 4] %} {# Tests the result #} {% for int in integer_array %} {{ int }} {% endfor %} ```
The result will be ``` 1 2 3 4 ```
## Set a floating number array to a variable ```twig {% set float_array = [1.1, 2.2, 3.3, 4.4] %}
{# Tests the result #} {% for float in float_array %} {{ float }} {% endfor %} ```
The result will be ``` 1.1 2.2 3.3 4.4 ```
## Set key-value pairs to a variable, and the key is string ```twig {% set map_str_key = {'one': 'first', 'two': 'second', 'three': 'third'} %} {# Tests the result #} {% for key, value in map_str_key %} [{{ key }}] = {{ value }} {% endfor %} ```
The result will be ``` [one] = first [two] = second [three] = third ```
## Set key-value pairs to a variable, and the key is integer ```twig {% set map_int_key = {1: 'first', 2: 'second', 3: 'third'} %} {# Tests the result #} {% for key, value in map_int_key %} [{{ key }}] = {{ value }} {% endfor %} ```
The result will be ``` [1] = first [2] = second [3] = third ```
If we store key as an integer, we can use square brackets(`[]`) to manipulate this variable: ```twig {# this will throw an error [0] = {{ map_int_key[0] }} #}
[1] = {{ map_int_key[1] }} [2] = {{ map_int_key[2] }} [3] = {{ map_int_key[3] }} ```
The result is: ``` [1] = first [2] = second [3] = third ```
When we use this approach to manipulate the variable, we must be careful that does not access the key which doesn't exist. Otherwise, an error will be thrown.
## Set a block of value to the variable The `set tag` not only accepts a line of value but also accepts a multiple lines value. Let's see how to implement it. If we want to use a set block to set value, the value should be enclosed by `{%set ... %}` and `{% endset %}`. ```twig {% set integer_array = [1,2,3,4] %} {% set ints %} <ol> {% for int in integer_array %} <il>{{ int }}</il> {% endfor %} </ol> {% endset %} {# Shows the result #} {{ ints }} ```
The result is ```html <ol> <il>1</il> <il>2</il> <il>3</il> <il>4</il> </ol> ```
However, the `{% set ... %} ... {% endset %}` code block doesn't convert JSON string into an object and it cannot be used to assign key-value pairs: ```twig {% set home %} { 'door': 4, 'room': 2, 'toilet': 1 } {% endset %} {# Shows the result #} {{ home }} {# this doesn't show anything #} {% for item in home %} {{ item }} {% endfor %} {# this will throw error #} {{ home['door'] }} ```
The result is: ``` { 'door': 4, 'room': 2, 'toilet': 1 } ```
As a result, the `{% set ... %} ... {% endset %}` code block only treats the value as text as the demonstration in the [official document](https://twig.symfony.com/doc/2.x/tags/set.html). If we use HTML tags assigned to the variables in this sort of code block and automatic output escaping is enabled, the HTML tags will be encoded to make sure the content is safe. ```twig {% set trh = '<tr>' %} {% set tre = '</tr>' %} {% set tdh = '<td>' %} {% set tde = '</td>' %} {% set table %} <table> {{ trh }} {{ tdh }} cell 1 {{ tde }} {{ tdh }} cell 2 {{ tde }} {{ tdh }} cell 3 {{ tde }} {{ trh }} {{ trh }} {{ tdh }} cell 4 {{ tde }} {{ tdh }} cell 5 {{ tde }} {{ tdh }} cell 6 {{ tde }} {{ trh }} </table> {% endset %} {# shows the result #} {{ table }} ```
The result will be: ```html <table> &lt;tr&gt; &lt;td&gt; cell 1 &lt;/tr&gt; &lt;td&gamp;t; cell 2 &lt;/tr&gt; &lt;td&gt; cell 3 &lt;/tr&gt; &lt;tr&gt; &lt;tr&gt; &lt;td&gt; cell 4 &lt;/tr&gt; &lt;td&gt; cell 5 &lt;/tr&gt; &lt;td&gt; cell 6 &lt;/tr&gt; &lt;tr&gt; <table> ``` ## Variable Scope If a variable has been declared inside a `for` loop, it cannot be accessed outside of the loop. ```twig {% set list=[1,2,3,4,5] %} {% for i in list %} {% set result = i %} {% endfor %} {# An error will be thrown #} {{ result }} ```
But it can be accessed if it has been declared outside the loop: ```twig {% set list=[1,2,3,4,5] %} {% set result = 0 %} {% for i in list %} {% set result = i %} {% endfor %} {# The result is 5 #} {{ result }} ```
# Filter A filter can be applied to the variables to trim space, lowercase all of the characters, merge an array and so on. ```twig {% set name = ' Kitty' %} {# this will print 'Kitty' instead of ' Kitty' #} {{ name }} ```
This will be introduced in the next tutorial.
# Reference [Twig Variables](https://twig.symfony.com/doc/2.x/templates.html#variables) [set Tag](https://twig.symfony.com/doc/2.x/tags/set.html) ## Relevant Readings [How to setup development environment for Twig on MacOS](https://totsi04.blogspot.com/2019/02/tutorial-how-to-setup-development.html)

Comments

Popular Posts