Forum

Thread tagged as: Question

Displaying categories at runtime in order to use PerchSystem::set_var

I've outputted a list of categories that I'm using as a category filter and I'd like to add a class to the currently selected filter - ideally using perch and not javascript. I stored the query string in a variable using PerchSystem::set_var (say the query is ?category=e-homes) and I was planning on doing something clever with that variable and comparing against the catSlug using <perch:if> to determine whether an active class gets added (whether this will work is currently untested), however I've just discovered that you can only use variables set by PerchSystem in templates parsed at runtime.

Is there a way that I can output my list of categories at runtime? I've looked in the categories runtime script and can't see something along the lines of perch_categories_custom.

Has anyone done something similar to what I'm trying to achieve?

Jon Young

Jon Young 0 points

  • 6 years ago
Drew McLellan

Drew McLellan 2638 points
Perch Support

Category templates are parsed at runtime, so there should be no issue there.

This is what I'm doing:

// Store the query string in a variable. TODO:  Can this be used?
            PerchSystem::set_var('project_category', perch_get('category'));

            perch_categories(array(
                'set'       => 'projects',
                'template'  => 'projects_filter.html'                   
            ));

..and then my template:

<perch:before>
<div class="filter-bar group container">
    <div class="row">
        <ul>
            <li class="filter-bar--all">
                <a href="/projects">all</a>
            </li>
</perch:before>
            <li class="filter-bar--by-type">
                <perch:content id="project_category" />
                <a href="?category=<perch:category id="catSlug" />"><perch:category id="catTitle" /></a>
            </li>
<perch:after>
        </ul>
    </div>
</div>
</perch:after>

Nevermind Drew - I needed to change <perch:content id="project_category" /> to <perch:category id="project_category" />

Works now ;-)

For anyone wanting to know, this is how my template ended up:

<perch:before>
<div class="filter-bar container">
    <div class="row">
        <ul>
            <li class="filter-bar--all<perch:if id="project_category" match="eq" value=""> active</perch:if>">
                <a href="/projects">all</a>
            </li>
</perch:before>
            <li class="filter-bar--by-type<perch:if id="project_category" match="eq" value="{catSlug}"> active</perch:if>">
                <a href="?category=<perch:category id="catSlug" />"><perch:category id="catTitle" /></a>
            </li>
<perch:after>
        </ul>
    </div>
</div>
</perch:after>