4

I’m passing the ID of a category to a template via a catId query string (i.e. http://example.com/some/path?catId=10).

How do I display the title of that category?

4

First you’ll need to grab the category ID from the query string, using craft.request.getQuery():

{% set catId = craft.request.getQuery('catId') %}

Then you can fetch the CategoryModel via craft.categories and its id param:

{% set category = craft.categories.id(catId).first() %}

We can’t be sure that the ID was actually valid, so make sure that category is actually set to something, otherwise return a 404 error:

{% if not category %}
    {% exit 404 %}
{% endif %}

Now, to output the category’s title, just do this:

{{ category.title }}

There are a couple ways you can put this all together, depending on whether the page requires a category ID passed to it, or if it’s optional.

If it’s required, we should verify that the catId query parameter was actually set to something right off the bat:

{% set catId = craft.request.getQuery('catId') %}

{# The catId param is required #}
{% if not catId %}
    {% exit 404 %}
{% endif %}

{% set category = craft.categories.id(catId).first() %}

{% if not category %}
    {% exit 404 %}
{% endif %}

{{ category.title }}

If it’s optional, then we should grab the ID from the query string, and then wrap all of the remaining logic in a conditional, so it only runs if there was an ID:

{% set catId = craft.request.getQuery('catId') %}

{# The catId param is optional #}
{% if catId %}
    {% set category = craft.categories.id(catId).first() %}

    {% if not category %}
        {% exit 404 %}
    {% endif %}

    {{ category.title }}
{% endif %}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.