Skip to Main Content

Shared Category and Listing Template in Craft

I've been working on re-launching this site in Craft CMS and there are two remaining bits to take care of. One of those is getting the blog categories to work. The default way to do this is to set up a separate template just for categories.

I didn't want to do that as the design of the blog landing page and category landing page is exactly the same. I prefer to keep my templating dry and having duplicate templates wasn't going to achieve that.

I posted a question on the Craft Stack Exchange site and got a response that solved this for me and keeps everything dry and works with pagination. So basically you set the parementers for craft.entries with a conditional and merge them if categories are set:

    
    
      {% set params = { section: 'blog', limit: 6 } %}
{% if category is defined %}
  {% set params = params | merge({ relatedTo: category }) %}
{% endif %}
    
  

This checks checks if the category is set and then restricts results related to the category. My final code with the for loop and pagination is here:

    
    
      {% set params = { section: 'blog', limit: 6 } %}
{% if category is defined %}
  {% set params = params | merge({ relatedTo: category }) %}
{% endif %}

{% set blogEntries = craft.entries(params) %}
{% paginate blogEntries as pageInfo, pageEntries %}


{% for entry in pageEntries %}
  <article class="col-sm-6 block" data-mh="blog-rows">

    more code here

  </article><!--block-->

{% endfor %}
    
  

The final piece to iron out before launching this site in Craft is getting my blog comments imported to disqus. Almost there.

More Articles You May Like