skip to Main Content

The result of what I was expecting is not the desired one..
The output of the table, is messing up because of it.

The result

so… the code is this one:

{% if (log.action) == "update"%}
    <td style="width: 150px; background-color: yellow;" >{{log.action}}
{% else %}
    {% if (log.action) == "insert"%}
        <td style="width: 150px; background-color: green;" >{{log.action}}
    {% endif %}
    <td style="width: 150px; background-color: red;" >{{log.action}}
{% endif %}

and what I need from it is just to print with background-color when the output string is equal to those 3 options (only those are the options).

2

Answers


  1. The current structure leads to rendering multiple <td> tags for the same condition, causing the output to be messy. Instead of above code, use single <td> for all your conditions.

    <td style="width: 150px; 
        {% if log.action == 'update' %} 
            background-color: yellow; 
        {% elseif log.action == 'insert' %} 
            background-color: green; 
        {% else %} 
            background-color: red; 
        {% endif %}">
        {{ log.action }}
    </td>
    
    Login or Signup to reply.
  2. Instead of nesting if‘s inside each other, consider an actual {% if %}...{% elseif %}..{% endif %}-structure

    {% if (log.action) == "update"%}
        <td style="width: 150px; background-color: yellow;" >{{log.action}}</td>
    {% elseif (log.action) == "insert"%}
        <td style="width: 150px; background-color: green;" >{{log.action}}</td>
    {% else %}
        <td style="width: 150px; background-color: red;" >{{log.action}}</td>
    {% endif %}
    

    demo


    A more clean solution would be to extend Twig and add a custom function/filter, e.g.

    <?php
        $twig = new TwigEnvironment($loader);
        $function = new TwigTwigFunction('get_background_color', function ($action) {
            switch($action) {
                case 'update':
                    return 'yellow';
                case 'insert':
                    return 'green';
                case 'delete':
                    return 'red';
                default:
                    return '';
            }
        });
        $twig->addFunction($function);
    
    <td style="width: 150px; background-color: {{ get_background_color(log.action) }};" >{{log.action}}</td>
    

    You could also drop the inline CSS and use classes of course e.g.

    <td class="{{ log.action }}" >{{log.action}}</td>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search