Working with Hierarchical Content

Using paths for maintaining tree structures

Especially with large amounts of content, tree structures can be handy because they can be used to represent the native structure of websites as the visitors see them. People tend to think in terms of pages, subpages, menus, submenus, and breadcrumb navigations. Hence, the tree structure of CMS objects comes naturally.

For creating and maintaining tree structures, every CMS object has a built-in _path attribute to which values such as “/news/politics/article42” can be assigned programmatically. However, explicitly assigning a path to a CMS object should only be required in situations where content needs to be restructured using a script. With in-place editing, Scrivito automatically generates and assigns paths as editors add pages to the website using the menu of a rendered toclist.

toclist is a built-in method of non-binary CMS objects that returns their non-binary child objects. Rendered using the scrivito_tag_list helper, editors will see a generated navigation that includes a menu with an item for creating a new page as part of this navigation. See Navigating the Page Hierarchy for details.

To programmatically traverse a hierarchy based on the _path attribute, the parent and children instance methods are available:

an_obj = Obj.find("55e783066434a5ba")
parent = an_obj.parent # => the parent Obj
parent.children # => this list of Obj contains an_obj
parent.path # => "/the/path/to"
an_obj.path # => "/the/path/to/an_obj"

Note that using paths is optional. If you decided to utilize paths and manipulate them programmatically, keep in mind that Scrivito does not validate paths with respect to uniqueness and the existence of their components. As a result, you can assign any formally correct path to a CMS object, specifying, for example, a nonexistent parent object as in "/articles/nonexistent/article20." Thus, next to the root object, all objects whose parent component in their path does not exist have a nil parent object. The same holds true for the children of an object. If none exist, the children list is empty regardless of whether there are descendants at a deeper hierarchy level or not.

Alternatives to using paths

If you don't require paths as a means to structure your content or for having navigations generated automatically, have a look at reference lists. They are predestined for maintaining navigations manually.

If you are mainly interested in having nicer URLs, consider using permalinks or fine-tuning the routing of your app.