For simplicity, I'm building a site for a restaurant. The "Menu" page has the following url(s):
mysite.com/food/appetizers
mysite.com/food/sandwiches
food
is a structure. It contains every entree the restaurant has. I've nested the actual entree to under the corresponding category. For example:
mysite.com/food/appetizers
/cheese-curds
/french-fries
mysite.com/food/sandwiches
/whole-sandwich
/half-sandwich
..and so on.
On mysite.com/food/
I can render all entrees under thier corresponding category like this:
{% set entries = craft.entries.section('food') %}
{% for entry in entries %}
{% if entry.type == 'category' %}
<h3><a href="{{ entry.getUrl }}">{{ entry.title }}</a></h3>
{% endif %}
{% set children = entry.getChildren() %}
{% for child in children %}
<h5><a href="{{ child.getUrl }}">{{ child.title }}</a></h5>
{% endfor %}
{% endfor %}
Everything is working great. All entrees are listed below their corresponding "category" on my /food/
page. I can click on each individual entree "cheese-curds" for example, and can get the entry details.
For templates I have _entry
and index
.
index
is used on mysite.com/food
_entry
is used on each entree.
Where I'm stuck is how to render the entries for the current category. For example:
mysite.com/food/appetizers
I'm not sure How to get past my initial command of getting ALL entires:
{% set entries = craft.entries.section('food') %}
{% for entry in entries %}
{% if entry.type == 'category' %}
....
....
To only this:
{% if entry.type == 'category' %}
....
....
So that I am only listing out the entries for the current category. It's OK if I need to create a new template, I'm not sure how to tell Craft how to do that. Or is there a better approach to getting all entries for the structure? It seems simple enough in theory, I keep talking myself in circles.
EDIT
Thank you @j00lz Your solution makes perfect sense. I think I either don't quite understand, or I'm still at the same spot I was before.
{% switch entry.level %}
{% case 1 %}
{# this is mysite.com/food #}
{# outputs #}
Appetizers
Cheese Curds
French Fries
Sandwiches
Sandwich One
Sandwich Two
{% case 2 %}
{# this is mysite.com/food/appetizers
{# outputs #}
Appetizers
Cheese Curds
French Fries
{% case 3 %}
{# this is mysite.com/food/appetizers/french-fries
{# outputs #}
French Fries
French fries are awesome!
{% endswitch %}
So, it's like I need another template to only show the 2nd case on the page. I can list all foods, and the actual entrée (3rd case) using 2 templates. I'm hung up on that middle page where it would only list the title of the entrée, and then the children entrée.
I thought about putting an if
statement at the top of the page that checks the URL level. If it's only /food/
do "x", if its /food/appetizers
do "y", but that seems to assume an awful lot.
Maybe there is a better route to go all together. I only had a structure in mind because of the nested elements that I wanted to be able to control where they were.