Skip to content
Advertisement

How to set if clause in twig?

I have these two functions:

function is_expired($object) {
              if (new DateTime('NOW') > $object) {
                  return true;
              } else {
                  return false;
              }
}

function is_not_started($object) {
              if (new DateTime('NOW') < $object) {
                  return false;
              } else {
                  return true;
              }
}

$object is Datetime object fetched from db. and I also registered functions as twig filter.

For a voting system I have two fields start_date and expiry_date, I want to see if this is not expired but already started.

In twig I have:

{% if (category.endVote|is_expired == false) or (category.startVote|is_not_started == true) %}
<td><a href="voting.php?id={{ category.id }}">{{ category.categoryName|e }}</a></td>
{% else %}
<td>{{ category.categoryName|e }}</td>
{% endif %}

I mean I want to see categoryName as link only if this is started and is NOT expired. but it doesn’t work as expected. What wrong I did in my if clause?

Advertisement

Answer

This is what I would recommend.

function can_vote($object) {
    $now = new DateTime('now');
    return $object->getEndVote() < $now && $object->getStartVote() > $now;
}

{% if category|can_vote is same as(true) %}
    <td><a href="voting.php?id={{ category.id }}">{{ category.categoryName|e }}</a></td>
{% else %}
    <td>{{ category.categoryName|e }}</td>
{% endif %}

Instead of two separate functions, merge these into one and pass in the entire category object. Also in the twig part, I recommend to use the more stricter equation instead of “==” the one in my code equates to “===”. Make note of the getEndVote() and getStartVote() getter methods, if You use public properties, change those to reflect the correct names.

If you wish to use two separate methods in the end it is not difficult to extract that functionality but i think this is a better solution.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement