How to create a counter with TWIG?

落爺英雄遲暮 提交于 2020-06-29 06:42:58

问题


I have a site with Drupal 8 and I want to create a task counter with TWIG.

I use views with conditions. The counter must be incremented whether the view has a result or not.

Here is the code I just made :

<span class="badge badge-warning task-badge-warning">
  {% if drupal_view_result('boutique_page_liste_des_taches_produit_non_publie', 'block_1') is not empty %}
    1
  {% endif %}
  {% if drupal_view_result('boutique_page_liste_des_taches_role_marchand', 'block_1') is empty %}
    1
  {% endif %}
</span>
<span class="badge badge-danger task-badge-danger">
  {% if drupal_view_result('boutique_page_liste_des_taches_aucun_produit', 'block_1') is empty %}
    1
  {% endif %}
  {% if drupal_view_result('boutique_page_liste_des_taches_aucune_variation', 'block_1') is not empty %}
    1
  {% endif %}
  {% if drupal_view_result('boutique_page_liste_des_taches_commande', 'block_1') is not empty %}
    1
  {% endif %}
  {% if drupal_view_result('boutique_page_liste_des_taches_mode_de_livraison', 'block_1') is empty %}
    1
  {% endif %}
  {% if drupal_view_result('boutique_page_liste_des_taches_passerelle_de_paiement', 'block_1') is empty %}
    1
  {% endif %}
</span>

There are 2 counters :

  • a "Warning" badge
  • a "Danger" badge

Do you know a solution to do this ?

  • The "Warning" badge must display the total number of "Warning" tasks.
  • The "Danger" badge must display the total number of "Danger" tasks.

回答1:


You can set variables and then increment them:

{% set warnings = 0 %}
<span class="badge badge-warning task-badge-warning">
  {% if drupal_view_result('boutique_page_liste_des_taches_produit_non_publie', 'block_1') is not empty %}
    {% set warnings = warnings + 1 %}
  {% endif %}
  {% if drupal_view_result('boutique_page_liste_des_taches_role_marchand', 'block_1') is empty %}
    {% set warnings = warnings + 1 %}
  {% endif %}
  {{ warnings }}
</span>
{% set dangers = 0 %}
<span class="badge badge-danger task-badge-danger">
  {% if drupal_view_result('boutique_page_liste_des_taches_aucun_produit', 'block_1') is empty %}
    {% set dangers = dangers + 1 %}
  {% endif %}
  {% if drupal_view_result('boutique_page_liste_des_taches_aucune_variation', 'block_1') is not empty %}
    {% set dangers = dangers + 1 %}
  {% endif %}
  {% if drupal_view_result('boutique_page_liste_des_taches_commande', 'block_1') is not empty %}
    {% set dangers = dangers + 1 %}
  {% endif %}
  {% if drupal_view_result('boutique_page_liste_des_taches_mode_de_livraison', 'block_1') is empty %}
    {% set dangers = dangers + 1 %}
  {% endif %}
  {% if drupal_view_result('boutique_page_liste_des_taches_passerelle_de_paiement', 'block_1') is empty %}
    {% set dangers = dangers + 1 %}
  {% endif %}
  {{ dangers }}
</span>


来源:https://stackoverflow.com/questions/62459527/how-to-create-a-counter-with-twig

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!