Using template conditionals with arrays (YouTube field type)

  • How can I test if the youtube video has a description? In other words, since the youtube_video id is an array, how can I test for the description key only?

    Code
    1. //This doesn't work!
    2. <perch:if exists="youtube_video" output="description">
    3.     <perch:content id="youtube_video" type="youtube" output="description"/>
    4. <perch:else>
    5.     Output something else
    6. </perch:if>
  • drewm

    Approved the thread.
  • The <perch:if> tag doesn't work with the output attribute. Your best bet would be to use the each option in perch_content_custom and add a key if the description exists


    Code
    1. perch_content_custom('Videos', [
    2.     'each' => function($item) {
    3.                 if($item['youtube_video']['description']) {
    4.                     $item['youtube_has_description'] = true;
    5.                 }
    6.               }
    7. ])

    Then in the template you can use

    Code
    1. <perch:if exists="youtube_has_description">
    2. <perch:content id="youtube_video" type="youtube" output="description"/>
    3. <perch:else>
    4. Output something else
    5. </perch:if>

    You'll likely need to tweak the above so it works correctly, haven't used the youtube field type before.

  • You'll have to loop through each block individually as well. Can't remember the exact syntax, but you can always do a var_dump() to get the exact structure of the array returned

    Code
    1. perch_content_custom('Videos', [
    2. 'each' => function($item) {
    3.                 foreach($item['_blocks] as &$block) {
    4.     if($block['youtube_video']['description']) {
    5.     $block['youtube_has_description'] = true;
    6.     }
    7.     }
    8.               }
    9. ])