Back

Pull Nested Child Categories by Parent Category Key

Description

Use this example to create dynamic parent/child category listings.  The category listings can then become clickable listings to filter content by category.. used in menus, etc...

Code

${esc.hash}${esc.hash}set the myCategoryKey variable to your parent category key name (see properties on your category and make sure it is set)
${esc.hash}${esc.hash}this example will show you how to pull the children and nested children of a category

${esc.hash}set(${esc.dollar}myCategorykey = "yourCatKey")

${esc.hash}foreach(${esc.dollar}con in ${esc.dollar}categories.getChildrenCategoriesByKey("${esc.dollar}!{myCategorykey}"))
<h2>${esc.dollar}velocityCount. Parent Category Properties</h2>
<p><strong>Velocity Variable Parent Category Name:</strong> ${esc.dollar}!{con.categoryVelocityVarName}<br/>
	<strong>Parent Category Name:</strong> ${esc.dollar}!{con.categoryName}<br/>
	<strong>Parent Category Key:</strong> ${esc.dollar}!{con.key}
</p>

	<h4>Pull of Next Level Child Category Names</h4>
	${esc.hash}foreach(${esc.dollar}child in ${esc.dollar}categories.getChildrenCategoriesByKey("${esc.dollar}!{con.key}"))
<p>
	<ul>
		<li>${esc.dollar}!{child.categoryName}</li>
		
${esc.hash}${esc.hash}Here in the list you could href a url map pattern that includes the category and go to a detail page that lists content by category based on the path: /someMapPattern/somecategory/ (see url map doc here http://www.dotcms.com/docs/latest/URLMapSEOFriendlyURLs)

	</ul>
</p>
	${esc.hash}end
<hr/>
${esc.hash}end
${esc.hash}${esc.hash}Keep nesting foreach loops in the "Pull of Next Child Category Names" to dig deeper into your category lists

Have you created code you'd like to share with the dotCMS community?

Share your code Become a Contributor