Categories Viewtool

CategoriesWebAPI, or $categories, is a Velocity ViewTool that allows you to work with categories in dotCMS templates and scripts.

The tool is automatically initialized by the Velocity framework and extracts the current user from the HTTP session; all methods are called with $categories, such as in the following three identical calls in different Velocity syntactic styles:

$categories.getCategoryByKey("category-key")
${categories.getCategoryByKey("category-key")}
$!{categories.getCategoryByKey("category-key")}

All category operations respect the user's permissions.

Viewtool Methods#


Each of these methods requires the $categories namespace.

MethodParametersReturn TypeDescription
getChildrenCategoriesByKeyString keyList<Category>Retrieves all child categories for a parent category identified by its key
getCategoryByKeyString keyCategoryFinds and returns a single category by its unique key
getChildrenCategoriesCategory catList<Category>Gets all child categories of the specified parent category
getChildrenCategoriesString inodeList<Category>Gets child categories for a parent identified by inode string
getChildrenCategoriesString inode, boolean includeGrandChildren, int maxDepthList<Category>Retrieves categories and their descendants up to the specified depth level
getActiveChildrenCategoriesCategory catList<Category>Gets all active child categories of the specified parent
getActiveChildrenCategoriesString inodeList<Category>Gets active child categories for a parent identified by inode string
getActiveChildrenCategoriesByKeyString keyList<Category>Gets active child categories for a parent identified by key
getActiveChildrenCategoriesByParentArrayList<String> oList<Category>Gets active children for multiple parent categories identified by keys or names
getActiveChildrenCategoriesOrderByNameCategory catList<Category>Gets active child categories sorted alphabetically by name
getActiveChildrenCategoriesOrderByNameString inodeList<Category>Gets active child categories sorted by name for parent inode string
getAllActiveChildrenCategoriesString inodeList<Map<String, Object>>Retrieves all active descendant categories with level information for parent inode string
getAllActiveChildrenCategoriesByKeyString keyList<Map<String, Object>>Retrieves all active descendant categories (any depth) with level information
getInodeCategoriesString inodeList<Category>Gets parent categories associated with an inode string
getCategoryByInodeString inodeCategoryFinds and returns a category by its inode identifier
getCategoryKeyByContentletString contentletInodeStringReturns the key of the first parent category for a contentlet
filterCategoriesByUserPermissionsList<Object> catInodesList<Category>Filters a list of category inodes based on current user's permissions
fetchCategoriesInodesList<Category> catsList<String>Extracts and returns a list of inode strings from category objects
fetchCategoriesNamesList<Category> catsList<String>Extracts and returns a list of category names from category objects
fetchCategoriesKeysList<Category> catsList<String>Extracts and returns a list of category keys from category objects

Category Object Methods and Properties#


Category objects retrieved with the viewtool represent hierarchical category entities. The methods and properties below are used with the retrieved objects, rather than the viewtool itself.

Properties / Getters#

The properties below are aliases of getter methods; a standard dotCMS Velocity pattern is that get methods without arguments can be simplified by removing the get and lowercasing the following character. As such, inode, below, can also be expressed as getInode().

PropertyTypeDescriptionDefault Value
inodeStringUnique inode for the categoryEmpty string if not set
categoryNameStringDisplay name of the category-
descriptionStringDetailed description of the categorynull
keyStringUnique key identifier for the category-
sortOrderIntegerNumeric value determining display order0
activebooleanWhether the category is active/enabledtrue
keywordsStringKeywords associated with the category for search/tagging-
categoryVelocityVarNameStringVelocity variable name associated with the category-
modDateDateLast modification dateCurrent date
mapMap<String, Object>Map representation of the category{inode=xxx, sortOrder=0, ...}
parentPermissionablePermissionable objectReturns the parent permissionable object (parent category or host)System Host
typeStringObject type name"category"
manifestInfoManifestInfoReturns manifest information for publishing/bundling operations-

Setter Methods#

Modifying most content in the dotCMS system requires a Workflow operation. However, Velocity setter methods for categories will immediately modify the category within the dotCMS system, and subsequent get calls will reflect the last set value.

MethodParametersDescription
setInode(String inode)String inodeSets the category's inode identifier
setCategoryName(String categoryName)String categoryNameSets the category's display name
setDescription(String description)String descriptionSets the category's description
setKey(String key)String keySets the category's unique key
setSortOrder(Integer sortOrder)Integer sortOrderSets the sort order (null values default to 0)
setSortOrder(String sortOrder)String sortOrderSets the sort order from a string (parses to Integer)
setActive(boolean active)boolean activeSets whether the category is active
setKeywords(String keywords)String keywordsSets the category's keywords
setCategoryVelocityVarName(String name)String nameSets the Velocity variable name
setModDate(Date modDate)Date modDateSets the modification date

Utility Methods#

MethodParametersReturn TypeDescription
hasActiveChildren()nonebooleanChecks if the category has any active child categories
toString()noneStringReturns a string representation of the category with all properties

Permission-Related Methods (Permissionable Interface)#

MethodParametersReturn TypeDescription
acceptedPermissions()noneList<PermissionSummary>Returns list of permission types applicable to categories (use, add-children, edit, edit-permissions)
getParentPermissionable()nonePermissionableReturns the parent permissionable object (parent category or host)
isParentPermissionable()nonebooleanAlways returns true - categories inherit permissions from parents

Usage Examples#


Get and Display Child Categories by Key#

## Get child categories of a category with a key of "products"
#set($childCategories = $categories.getChildrenCategoriesByKey("products"))

<ul>
#foreach($category in $childCategories)
    <li>$category.categoryName</li>
#end
</ul>

Retrieve a Single Category and Display Its Properties#

## Get a specific category by key
#set($productCategory = $categories.getCategoryByKey("electronics"))

#if($productCategory)
    <h2>$productCategory.categoryName</h2>
    <p>Category Key: $productCategory.key</p>
    <p>Category Inode: $productCategory.inode</p>
    <p>Category Description: $productCategory.description</p>
    <p>Category Sort Order: $productCategory.sortOrder</p>
#end

## Alternative: examine by map
#set($categoryMap = $productCategory.map)

## Access properties from map
<ul>
    <li>Name: $categoryMap.get("categoryName")</li>
    <li>Description: $categoryMap.get("description")</li>
    <li>Key: $categoryMap.get("key")</li>
    <li>Inode: $categoryMap.get("inode")</li>
</ul>

Get Nested Categories with Depth Levels#

## Get all descendant categories with their hierarchy levels
#set($allCategories = $categories.getAllActiveChildrenCategoriesByKey("main-menu"))

#foreach($categoryMap in $allCategories)
    #set($level = $categoryMap.get("level"))
    #set($category = $categoryMap.get("category"))
    
    ## Indent based on level
    #foreach($i in [1..$level])
        &nbsp;&nbsp;
    #end
    - $category.categoryName (Level $level)<br/>
#end

For an alternate aproach to climbing category trees: You can also check for active children from an already-fetched category, using the object's methods.

#set($parentCategory = $categories.getCategoryByKey("main-menu"))

#if($parentCategory.hasActiveChildren())
    <p>This category has active subcategories</p>
    #set($children = $categories.getActiveChildrenCategories($parentCategory))
    <ul>
    #foreach($child in $children)
        <li>$child.categoryName</li>
    #end
    </ul>
#else
    <p>No active subcategories</p>
#end

Get Categories Associated with Content#

## Get all categories assigned to a specific contentlet
#set($contentCategories = $categories.getInodeCategories($contentlet.inode))

#if($contentCategories && $contentCategories.size() > 0)
    <div class="content-tags">
    #foreach($cat in $contentCategories)
        <span class="tag">$cat.categoryName</span>
    #end
    </div>
#end

Get Active Categories Sorted by Name#

## Get active child categories sorted alphabetically
#set($sortedCategories = $categories.getActiveChildrenCategoriesOrderByName("parent-category-inode"))

<select name="category">
    <option value="">Select a category...</option>
    #foreach($category in $sortedCategories)
        <option value="$category.inode">$category.categoryName</option>
    #end
</select>

Get Immediate Child-Category Keys#

## Get all immediate child categories and extract their keys
#set($productCategories = $categories.getChildrenCategoriesByKey("products"))
#set($categoryKeys = $categories.fetchCategoriesKeys($productCategories))

## Use the keys for further processing
#foreach($key in $categoryKeys)
    Category Key: $key<br/>
#end

Toolbox Mapping#


The following example shows how the CategoriesWebAPI Viewtool is mapped in the toolbox.xml file:

    <tool>
        <key>categories</key>
        <scope>request</scope>
        <class>com.dotcms.rendering.velocity.viewtools.CategoriesWebAPI</class>
    </tool>