Alexander Solonik Alexander Solonik - 24 days ago 5x
Twig Question

what is if not and ct.viewless|default(false) in twig?

I just came across the following syntax in the bolt CMS :

{% for ct in app.config.get('contenttypes') if not ct.viewless|default(false) %}

Now the start of the loop seems familiar PHP syntax but the part where the below comes into the picture:

if not ct.viewless|default(false)

Now That part is a bit harder to understand , what is that part of the code really doing ??

or actually what is that part of the code really saying ??

P.S. The above syntax is Twig syntax which is a php templating language.


The code you posted loop for all the values of the contenttypes, if the values of the element in the loop haven't the property viewlessor that property is false then will enter in the loop.

From the doc of the Twig loop:

Adding a condition

Unlike in PHP, it's not possible to break or continue in a loop. You can however filter the sequence during iteration which allows you to skip items. The following example skips all the users which are not active:

    {% for user in users if %}
        <li>{{ user.username|e }}</li>
    {% endfor %}

The advantage is that the special loop variable will count correctly thus not counting the users not iterated over. Keep in mind that properties like loop.last will not be defined when using loop conditions.

Hope this help