Spit HTML base on conditions


#1

Hello.
I have a snippet that fetches all the grandChildren of a specified page. What I want to do now is to output HTML tags depending on the grand child’s parent.

This is what my pages looks like:

MENU

  • Burgers

    • Burger 1
    • Burger 2
  • Sides

    • Sides 1
    • Sides 2

So my current snippet fetches all the grandChildren of Menu page. I need to output for example DIV tag if the parent is Burgers, else I would output SECTION if parent is Sides.

Of course I can achieve this with separate snippets but would like to do it in one snippet only.

Appreciate the help. Thank you.


#2

Of course this can be done with an if - else statement, but I’m wondering what your reasoning for this different markup is?


#3

Yes, if statement already comes to my mind but I have very limited PHP knowledge.
The examples I gave for spitting DIV and SECTION was just an example. What I really want to achieve is to spit different options base on the parent.

For the Burgers, i have a separate blueprint which has more fields. Same with the Sides, I have a blueprint with specific fields for it as well.


#4

I’d then create two different snippets named like the uid of the parent, for example burgers.php and sides.php (provided the UID of these pages cannot be changed, otherwise use a readonly field that cannot be changed), then in your loop:

foreach(page('menu')->grandchildren() as $child):
  snippet($child->parent()->uid(), ['page' => $child]);
endforeach

I think that results in cleaner code than:

foreach(page('menu')->grandchildren() as $child):
  //as above, this will only work if the uid of the burger parent doesn't change
  // otherwise use the value of a readonly field 
  if($child->parent()->uid() == 'burger'):
     // your burger child html
  else:
    // your sides child html
  endif
endforeach

#5

Always helpful. Thanks you sir!