Output entry category in ExpressionEngine
I'm trying to output the category of a channel entry in ExpressionEngine, so that I can use it as a CSS class on an HTML element — see my attempted usage of {category_name}
in the example below:
{exp:channel:entries
channel="panels"
disable="member_data|pagination|trackbacks|categories|category_fields"
status="open"
dynamic="no"
}
<div class="panel {category_name}">
<h4>{title}</h4>
{if panel_image}
<img src="{panel_image}" />
{/if}
<p>{panel_text}</p>
<a href="{panel_link}">{panel_link_text}</a>
</div>
{/exp:channel:entries}
As you can see, I'm trying to use the entry's category as a CSS styling 'hook' ... but I can't figure out how to output an entry's category in my template.
I'd prefer to avoid using PHP in my template. Does anyone know how to improve my code?
Wrap a Categories Tag Pair around your {category_name}
, which will output all of the categories assigned to an entry:
<div class="panel {categories}{category_name} {/categories}">
However, this will output the "pretty name" of your categories — which is undesirable for CSS classes or IDs on HTML elements:
<div class="panel Category One Category Two ">
Instead, use {category_url_title}
, which is a web safe version of a Category Name:
<!-- Categories Tag Pair code -->
<div class="panel {categories}{category_url_title} {/categories}">
<!-- Outputs the following -->
<div class="panel category_one category_two ">
Pay special attention to the extra space in the above examples, which is needed to separate multiple categories (CSS Classes) with a space.
If you're obsessive compulsive about your markup, you can use the backspace=
parameter to remove the trailing space when multiple categories are output:
{categories backspace="1"}{category_url_title} {/categories}
Should you wish to limit how many categories are output, or from which category group, use the Categories Tag Pair Parameters to suit your needs:
<!-- No whitespace is needed, since we're outputting only one category -->
{categories limit="1"}{category_url_title}{/categories}
Here's the entire code snippet for review:
{exp:channel:entries channel="panels" dynamic="no"}
<div class="panel {categories}{category_url_title} {/categories}">
<h4>{title}</h4>
{if panel_image}
<img src="{panel_image}" />
{/if}
<p>{panel_text}</p>
<a href="{panel_link}">{panel_link_text}</a>
</div>
{/exp:channel:entries}
链接地址: http://www.djcxy.com/p/66018.html
上一篇: 与表达式引擎相关的条目下拉值