Reputation: 71
I currently have a category dropdown filter set-up for my blog pages. This works to switch between the category pages, however, I am having difficulty getting the dropdown box to show the active category.
Here is what I have in my archive.php file
$context['categories'] = Timber::get_terms('category');
And here's the function that shows the current category dropdown.
<form id="category-select" class="category-dropdown" action="{{site.url}}" method="get">
<select name="cat" id="cat" class="cat-menu" onchange="return this.form.submit()">
<option value="-1">Select a category</option>
{% for cat in categories %}
<option class="level-0" value="{{cat.id}}">{{cat.name}}</option>
{% endfor %}
<option value="0">View All</option>
</select>
<noscript><input type="submit" value="View" /></noscript></form>
Does anyone have any guidance on how to this properly?
Upvotes: 1
Views: 1980
Reputation: 71
Thanks to @DarkBee I was able to figure this out. Didn't use exactly the code provided, but it pointed me in the right direction.
I found get_query_var( 'cat' ) would get the current category pages ID.
$post = Timber::get_post();
$post_categories = $post->terms('category');
$context['selected_category'] = get_query_var( 'cat' );
$context['categories'] = Timber::get_terms('category');
<form id="category-select" class="category-dropdown" action="{{site.url}}" method="get">
<select name="cat" id="cat" class="cat-menu" onchange="return this.form.submit()">
{% for cat in categories %}
<option class="level-0" value="{{cat.id}}"
{% if selected_category == cat.id %}
selected
{% endif %}>{{cat.name}}</option>
{% endfor %}
<option value="0">View All</option>
</select>
<noscript><input type="submit" value="View" /></noscript></form>
Upvotes: 1
Reputation: 15574
You have to pass the current category to the view. If your post only have one category you can use the following snippet,
controller.php
<?php
$post = Timber::get_post();
$post_categories = $post->terms('category');
$context['selected_category'] = reset($post_categories); //post can be attached to one or more categories
$context['categories'] = Timber::get_terms('category');
view.twig
<form id="category-select" class="category-dropdown" action="{{site.url}}" method="get">
<select name="cat" id="cat" class="cat-menu" onchange="return this.form.submit()">
<option value="-1">Select a category</option>
{% for cat in categories %}
<option class="level-0" value="{{cat.id}}"{% if selected_category is defined and selected_category.id = cat.id %} selected{% endif %}>{{cat.name}}</option>
{% endfor %}
<option value="0">View All</option>
</select>
<noscript><input type="submit" value="View" /></noscript></form>
Upvotes: 1