10

I need to output the category for an entry a few times in an entry's template.

So I want to get the output from the following and assign to a variable so I can reuse within the template:

{exp:channel:entries channel="product" limit="1" status="open"}
    {categories}{category_name}{/categories}
{/exp:channel:entries}"

How do it do that?

onblur
  • 365
  • 1
  • 5
  • 16

3 Answers3

9

Now, you could enable the template to allow PHP, then you could write something like this:

{exp:channel:entries channel="product" limit="1" status="open"}
    {categories}
        <?php $category = '{category_name}'; ?>
    {/categories}
{/exp:channel:entries}

Then you have the {category_name} stored in the php-variable "category". Later you can reuse it as you wish, like echoing it:

<?php echo $category; ?>

You can even compare it to other EE-tags:

{exp:channel:entries channel="product" limit="1" status="open"}
    {if <?php $echo($category) ?> == title}
        This title have got the same value as the category!
    {/if}
{/exp:channel:entries}
Marcus Olsson
  • 2,485
  • 19
  • 35
3

Croxton's Stash: http://devot-ee.com/add-ons/stash does very nearly the same thing NSM Transplant (mentioned by Derek, above) does, and is free. One of these addons would definitely be the easiest way to do what you're trying to do.

adrienne
  • 707
  • 1
  • 8
  • 24
2

EE has no built-in way to save data from within a tag loop and reuse it elsewhere in the template, outside of that tag loop.

One solution would be to use NSM Transplant to do exactly what you're looking to do.

Another would be to wrap your whole entry page in your channel:entries tag, so you can just use the categories loop wherever you need it, then use embeds for anything that can't be nested inside channel:entries.

Derek Hogue
  • 4,589
  • 1
  • 15
  • 27
  • Thanks, wasn't aware of NSM Transplant - looks like a nice solution but cost is a bit overkill for my particular situation. I actually wanted to use the code to grab the category_id and use that to filter a list of channel entries (list sibling entries). I put the code from my post and inserted into a template Snippet called {my_category} and put that into the category="" attribute of a channel entries call, but channel entries doesn't seem to evaluate the Snippet. So I'm just gonna resort to using embed templates and pass in the variables. – onblur Sep 26 '11 at 03:20
  • You should take a look at [related categories mode](http://expressionengine.com/user_guide/modules/channel/parameters.html#related_categories_mode). – Derek Hogue Sep 26 '11 at 13:03
  • (New link for my comment above: http://ellislab.com/expressionengine/user-guide/modules/channel/channel_entries.html#related-categories-mode) – Derek Hogue Apr 12 '13 at 16:20