1

I have a blog listing page which works correctly. I also have categories that I would like to use the same template rather than creating a whole new template since the design is exactly the same.

However when I set the category template to blog/index the page loads correctly but doesn't limit by categories.

Looking at my simplified template code, I'm not sure how to get it to display only the category being viewed or all if on the blog index page.

My urls are

/blog/
/blog/p2 (pagination)
/blog/{{ slug }}

I would like the following url's to use the same template code:

/blog/category/{{ category_url }}
/blog/category/{{ category_url }}/p2

My template code:

{% paginate craft.entries.section('blog').limit(6) as pageInfo, pageEntries %}
{% for entry in pageEntries %}
  <article class="col-sm-6 block" data-mh="blog-rows">

    some code

    <aside>
      more code
    </aside>

    <a href="{{ entry.url }}" class="btn btn-primary">Keep Reading</a>

  </article><!--block-->
{% endfor %}

If necessary I can create a category.html template, but then I'd essentially have duplicate code. Is there a way to do what I want to?

3

Yup, you can totally re-use the same template. When it is a category page, you will have access to a category variable which is a CategoryModel, and you can use that to filter your entries by category.

  • Trevor, how would I use the CategoryModel to limit the results to the category if on a category page and list all results if on a regular listing page. i.e. /blog/ or /blog/p2 vs /blog/category or /blog/category/p2 I looked at the docs for that page and it wasn't immediately clear how to do this. – CreateSean Oct 14 '16 at 13:58
  • {% set params = { section: 'blog', limit: 5 } %} {% if category is defined %} {% set params = params | merge({ relatedTo: category }) %} {% endif %} {% set blogEntries = craft.entries(params) %} – Trevor Davis Oct 17 '16 at 14:25
  • Thanks Travis, got this working and so simple, but I wouldn't never have figured it out on my own. – CreateSean Oct 18 '16 at 14:29
2

I'm confused: if the supplied code is what you're using for both the index page and category page then it won't filter by category because there's no code to tell it to do that.

Category would need something like:

{% set entries = craft.entries.relatedTo(category) %}
{% for entry in entries %}
    <li>
        <a href="{{ entry.url }}">
            <h2>{{ entry.title }}</h2>
            <p class="meta">Posted: {{ entry.postDate|date("d.m.Y") }}</p>
        </a>
    </li>
{% endfor %}

Rather than trying to use the same template - given the logic is actually slightly different - I'd perhaps suggest setting up a shared template to extend from (i.e., another _layout.twig).

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.