2

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.

9

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 %}
2

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.

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.