Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Twig: type of dynamic property

Tags:

php

twig

symfony

Currently, in my index page, I show the value of object properties from dynamic object and dynamic properties.

{% for object in objects %}
    <tr>
        {% for property in properties %}
            <td>{{ attribute(object, property) }}</td>
        {% endfor %}                  
    </tr>
{% endfor %}

Here both the objects and properties are dynamic. And I output the value of the property as attribute(object, property). But there are some properties with boolean type. Currently those boolean properties gives output as 0 or 1. I need to output no or yes instead of 0 or 1. How can I do that?

One option could be to find out the type of the property. But I don't know how I can get the type of the property from dynamic object and properties.

Edit: most answers are considering that all the properties are boolean type. But some of them are boolean and some of them are not boolean.

like image 393
asdfkjasdfjk Avatar asked Dec 07 '16 11:12

asdfkjasdfjk


2 Answers

If your attribute function only returns 0,1 You can try ternary operator too:

{% for object in objects %}
    <tr>
        {% for property in properties %}
            <td>{{ attribute(object, property) ? 'Yes' : 'No'}}</td>
        {% endfor %}                  
    </tr>
{% endfor %}

Edit: You can try in

{% set boolArray = [1, 0] %}

{% for object in objects %}
    <tr>
        {% for property in properties %}
            <td>
                {% if attribute(object, property) in boolArray %}
                    {{ attribute(object, property) ? 'Yes' : 'No'}}
                {% else %}
                    {{ attribute(object, property)}}
                {% endif%}
            </td>
        {% endfor %}
    </tr>
{% endfor %}
like image 178
vijaykumar Avatar answered Oct 05 '22 23:10

vijaykumar


Using same as

You may want to consider implementing a Twig conditional statement (which can be inserting into a Twig macro) using the same as Twig feature as so:

{% for object in objects %}
    <tr>
        {% for property in properties %}
            {% if attribute(object, property) is same as(true) %}
                <td>yes</td>
            {% elseif attribute(object, property) is same as(false) %}
                <td>no</td>
            {% else %}
                <td>{{ attribute(object, property) }}</td>
            {% endif %}
        {% endfor %}                  
    </tr>
{% endfor %}

As stated in the same as documentation:

same as checks if a variable is the same as another variable. This is the equivalent to === in PHP

like image 37
Alexandre Avatar answered Oct 05 '22 23:10

Alexandre