See the answers to our previous quiz about 20 questions that every Twig developer should be able to answer.

Answers and explanations to 20 Questions that every Twig Developer Should be Able to Answer

This article contains the answer to the previously published Test of 20 Questions that every Twig Developer should be able to answer.

1. How can you declare a variable in Twig?

  • C

This is the correct answer as the syntax to declare a variable follows the opening of {%, the name of the variable, an equal symbol to define its value and the value to assign:

{% set myVariable = 'My Text' %}

Read the set keyword in the official docs for more information.

2. What's the output of the following snippet?

{{ {name: "Xavier", lastName: "Nemo", first: false, address: "P Sherman, 42 Wallaby Way, Sydney"} | first }}
  • D

The output of the snippet would be "Xavier" as the first filter returns the first "element" of a sequence, a mapping, or a string. For more information about this filter, visit the official docs here.

3. What is the comment syntax for Twig?

  • D

Commented code in Twig starts with a bracket and a number sign and is closed respectively inverse. Anything inside a comment block won't be displayed on the view nor processed by Twig. The comment syntax supports multilines as well:

    Everything inside is a comment

4. The Output Escaping in Twig

  • A
  • B
  • D

Three answers are correct in this question. The escaping is enabled by default in Twig and it can be ommited by using the raw filter in the variable that has safe content. It offers therefore automatically protection for XSS attacks, so HTML tags won’t be parsed by the browser. Internally, escape uses the htmlspecialchars() PHP function.

5. Does Twig create a special variable in the scope of a for loop to get information about the current iteration? If it does, what is its name?

  • C

Inside of a for loop block you can access some special variables contained in the loop variable:

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

For more information about this special variable, read the official docs here.

6. What would be the output of the following snippet?

{% verbatim %}
    {% for row in rows %}
        <li title="{{ rows.title }}">{{ rows.text }}</li>
    {% endfor %}
{% endverbatim %}
  • B

The verbatim tag exists and allow you to write any Twig syntax inside the block, however this won't be parsed as twig but as Plain Text, so the output would be the same content inside the Verbatim block. For more information about this block, read the docs here.

7. Which of the following default filters doesn't exist in Twig?

  • A
  • E

An unescape or strtolower filter doesn't exist in Twig by default, however you can create such filters by creating a custom extension.

8. What is the output of the following snippet?

{% spaceless %}
    <div   class="welcome-alert">
        <h1 >Welcome David !</h1>
{% endspaceless %}
  • D

The correct option is D whose output is:

<div   class="welcome-alert"><h1 >Welcome David !</h1></div>

The simple reason is, that the spaceless block removes whitespaces between HTML tags, not whitespace within HTML tags or whitespace in plain text, therefore the other options aren't correct. To know more about this block, read the docs here

9. What is the correct syntax to concatenate strings?

  • C

You can concatenate strings by using the ~ (tilde) operator.

10. How can you verify if 2 variables are identical (important identical not equal)?

  • E

The same as test checks if a variable is the same as another variable. This is the equivalent to === in PHP, however in Twig this syntax is not preserved. For more information about this test, read the official docs here.

11. It's possible to use the same PHP constants in Twig by default?

  • C

You can retrieve the value of any PHP constant as long as it's available on PHP using the constant function that returns the value from the name of the constant that you need, for example to retrieve the value of the JSON_PRETTY_PRINT constant to print an idented JSON string, you would do:

{% set data = {
    "Hey": "Ho",
    "What": 12,
    "Value" : true

{{ data|json_encode(constant('JSON_PRETTY_PRINT'))}}

12. How can you print a random value from an array with Twig?

  • A

The random function returns a random value depending on the supplied parameter type:

  • a random item from a sequence
  • a random character from a string
  • a random integer between 0 and the integer parameter (inclusive).

In this case, the function is receiving an array, and from that array a random item will be selected. There is no random filter or randomize function.

13. How can you print the value of the "a-b" attribute from the following key-value array?

{% set MyVariable = {
    "a": 1,
    "b": 2,
    "c": 3,
    "a-b": 4
  • B
  • C

You can access properties from an array using the key notation or using the attribute function of Twig that expects as first argument the array and as second argument the property that you want to retrieve.

14. What is the output of the following snippet?

{% with %}
    {% set MyVariable = 42 %}
{% endwith %}

{{ MyVariable }}
  • A

With the with tag you can create a new inner scope. Variables set within this scope are not visible outside of the scope. As we are printing the MyVariable outside of the scope, the code will throw an exception. 

15. Which of the following tests keywords do not exist in Twig?

  • E

There is no test named instanceof in Twig, the rest of them exist though.

16. It is possible to print the content of an already existing block twice?

  • B

You can't declare a block twice, however you are able to retrieve the content of the block using the block function that expects as first argument the name of the block that you want to copy:

<title>{% block title %}{% endblock %}</title>

<h1>{{ block('title') }}</h1>

{% block body %}{% endblock %}

17. What is the output of the following snippet?

{% set items = ['a', 'b', 'c', 'd', 'e', 'f', 'g', "h"] %}

{% for row in items|batch(4) %}
        {%- for column in row -%}
            <td>{{ column }}</td>
        {%- endfor -%}
{% endfor %}
  • A

The batch filter exists and split an existing array into chunks from the size of the integer providen as first argument (it can be a number in string format as well). By splitting the given items array into chunks of the same size, we would have 2 rows generated on HTML for the table, so the options A and B are possible, however the space control providen in the for loop discards B as it shows the outputs without spaces, so A is the correct answer. For more information about the batch filter, read the official docs here.

18. What is the output of the following snippet?

{{ 12.4 // 2 }}
  • C

The answer is 6. The double slash operator, divides two numbers and returns the floored integer result. This is just syntactic sugar for the round filter.

19. Which of the following snippets allows to print the Alphabet separated by a comma?

  • A
  • D

Both options are correct as the range function returns a list containing an arithmetic progression of integers and characters. The Twig built-in .. operator is syntactic sugar for the range function (with a step of 1, or -1 if the start is greater than the end).

20. What is the output of the following snippet?

  • A

As we don't have any context, we can assume that the variable doesn't exist, so the default filter will be used. The default filter returns the passed default value if the value is undefined or empty, otherwise the value of the variable, that in this case, is a simple string namely "User is not logged in".

How many answers were correct in your test? We would be glad to hear about your results on the comment box.

Happy coding !

Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.