how to count items in an array

Support MB Views how to count items in an array

Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #47856
    swestswest
    Participant

    I have a View named "Topic title and byline".

    
    <h1>{{ post.topic_title }}</h1>
    {% set relationship = attribute( relationships, 'topic-to-team' ) %}
    {% for post in relationship.to %}
    	<h2>by {{ post.team_member_name }}</h2>
    {% endfor %}
    

    This works fine, but I need to handle the output differently based on the number of items in post.team_member_name. I have a Topic that usually has 1 Speaker (Team Member - post.team_member_name), but there may be as many as 3 Speakers in a few cases. In that case, the output reads:
    "by post.team_member_name One
    by post.team_member_name Two
    by post.team_member_name Three"

    when I need it to be:
    "by post.team_member_name One, post.team_member_name Two, and post.team_member_name Three"

    is there a way to count the number of items in "relationship" and then do one thing if that returns 1 and another if that returns > 1.

    Here's some pseudo code that should give you an idea of what I want to do. I've tried doing this in Twig in the View, but it always results in a fatal error.

    
    set myVariable to count the number of items in relationship
    if myVariable = 1
      output by post.team_member_name
    else
      output "by post.team_member_name One, post.team_member_name Two, and post.team_member_name Three"
    end if
    

    How would this be written in my view?

    #47876
    PeterPeter
    Moderator

    Hello,

    I suggest you use the length filter of the Twig code to get the number of items in an array. Please follow the documentation https://twig.symfony.com/doc/3.x/filters/length.html

Viewing 2 posts - 1 through 2 (of 2 total)
  • You must be logged in to reply to this topic.