2

I'm trying to stay as DRY as possible here and sharing one template for a news list view; all, category and tag all sharing the same template (and trying to refrain from having a category or tag segment). My query isn't returning any results when the segment 2 (in this case the url encoded tag or category slug) when there is a tag and category that share the same name. Example, 'design' is a category for design related posts; 'design' is a tag for posts that featured a design service within the 'portfolio' category. My template code is below. Is there a work around here or do I need to have a second segment for tag/category (i.e. .com/news/category/design and .com/news/tag/design - or one or the other to differentialte)

{% if category is defined %}

    {% set newsPosts = craft.entries.section('news').relatedTo(category).limit(5) %}

{% elseif tag is defined %}

    {% set tag = craft.tags.groupId(3).name(tag).first() %}

    {% set newsPosts = craft.entries.section('news').relatedTo(tag).limit(5) %}

{% else %}

    {% set newsPosts = craft.entries.section('news').limit(5) %}

{% endif %}

2 Answers 2

2

If the url for posts with the category design is .com/news/design and the url for posts with the tag design is also .com/news/design, then you are not going to be able to see both lists. You do need that extra segment in the url.

What I do to stay DRY is let Craft route tags and categories to different templates (so you don't have to repeat the is this a category or a tag logic). Then on the different templates, use a macro or include for the common code.

Here is what the categories page looks like with a macro:

{% extends '_layout' %}
{% import '_macros/_news' as news %}

{% set newsPosts = craft.entries.section('news')relatedTo(category).limit(5) %}

{% block content %}
  <h1>Entries with category {{category.title}}</h1>
  {{ news.index(newsPosts) }} {# all the shared code is in news.index() #}
{% endblock content %}
2

While Marion's post is right, it's not quite what I was trying to achieve I didn't want to have 2 templates (although use of macros is perfectly suitable).

What I've done to get around this is is add a tag segment for tags and leave categories as is. Then I added a custom route to support the tag segement but use the same template code

URI's:

/news/*category*

/news/tag/*tag*

The category route is defined automagically, but I needed to set up a route for the tag view.

Template Path:

news/index (which is also defined as my Category Template in the category settings)

Using the same template code above, I'm able to get the index/list view of a category and tag when they are the same all within the same template.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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