check stats when the page is load

2019-08-08 17:04发布

问题:

In my twig file i want to check the status ("ON/OFF") when the page load.

An example will be--- "Dell" is a host name, so when the page load it should check the status from entity whether it is "on/off". If it is ON, it should be green (btn-success) and if it is OFF it will be red ( btn-danger ).

My entity name is "userinfo" and i want to check whether it is True or false in the button when the page load.

This is what i try to implement, but i think i am doing it wrong ---

{if({ userinfo.stats=false }){ btn btn-danger}else {}}

{if({ userinfo.stats=true }){ btn btn-success}else {}}

this is my button group---

                    <td>
                        <div class="btn-group" data-toggle="buttons-radio">
                            <button class="btn btn-primary btn-xs myOn-button" ><i class="fa fa-check"></i> {% trans %}On{% endtrans %}</button>
                            <button class="btn btn-default btn-xs myOff-button" ><i class="fa fa-remove"></i> {% trans %}Off{% endtrans %}</button>
                        </div>
                    </td>

Do anyone knows how to solve this problem. Thanks in advanced.

回答1:

twig if statement you need to do with {%

{% if userinfo.stats %}
      {% set newClass = 'off' %}
{% else %}
      {% set newClass = 'on' %}
{% endif %}

or directly in the button

<button class="btn btn-primary btn-xs {% if userinfo.stats %}myOn-button{% else %}myOff-button{% endif %}" ><i class="fa fa-check"></i> {% trans %}On{% endtrans %}</button>


回答2:

Or you can try using ternary operator for a more concise way

<td>
    <div class="btn-group" data-toggle="buttons-radio">
        <button class="btn btn-primary btn-xs {{userinfo.stats ? 'myOn' : 'myOff'}}-button" ><i class="fa fa-{{userinfo.stats ? 'check' : 'remove'}}"></i> {% trans %}{{userinfo.stats ? 'on' : 'off'}}{% endtrans %}</button>
    </div>
</td>