Take the 2-minute tour ×
Craft CMS Stack Exchange is a question and answer site for administrators, end users, developers and designers for Craft CMS. It's 100% free, no registration required.

Forgive the simplicity of this question but I am in the early stages of my first Craft implementation.

My simple question is: how do I display a category name in a template. This is the code I am using:

{% for entry in craft.entries.find({section: 'blog', limit: '3'}) %}
    <div class="article">
        <p class="category">{{ entry.blogCategory }}</p>
        <a href="{{ entry.url }}" class="headline">{{ entry.title }}</a>
    </div>
{% endfor %}

The error I am getting says "Object of class Craft\ElementCriteriaModel could not be converted to string"

Any help is appreciated.

share|improve this question

2 Answers 2

up vote 6 down vote accepted

An ElementCriteriaModel is "used to fetch elements with a given set of parameters." {{ entry.blogCategory }} hasn't yet fetched your category element.

You need:

<p class="category">{{ entry.blogCategory.first }}</p>

if you are positive there is exactly one of them, or more generally:

{% for c in entry.blogCategory %}
  <p class="category">{{ c }}</p>
{% endfor %}
share|improve this answer
    
Thanks. So much to learn... –  jeff_nordstedt Jul 17 at 18:10
    
Thanks. You saved me from blowing up my MacBook Air. –  blairrorani Jul 25 at 8:55
    
Thank you! Helped me. –  Anna_MediaGirl Aug 26 at 19:56

There are several ways. Categories in Craft are elements. Most things are. I wrote an answer about relating elements here. For you, if you know there's just one you can:

<p class="category">{{ entry.blogCategory.first() }}</p>

If there's many you can loop over them:

{% for category in entry.blogCategory %}
    <p class="category">{{ category }}</p>
{% endfor %}

If you just want a comma separated list:

<p class="category">{{ entry.blogCategory.find()|join(", ") }}</p>

I haven't tried the last one, but it should theoretically work.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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