Anchor
Last updated: Jul 26, 2024

Introduction

The anchor element is a special element to dynamically create a table of contents and links to another part of the website. This is done by parsing the data input given by the user in the cms.

This very page uses the anchor to build the table of contents on the right side of this page.

Building an anchor navigation

When a anchor element is added to a sectio, the user will have to ability to create a table of contents linking to specific pieces of the page. The anchor input field is a regular text input field, where the user can specify a name for the anchor. It is also possible to nest up to 3 levels.

Lets say we have 3 sections on our page:
- Shoes
- Dresses
- Shorts

And we have under the Dresses section, 2 subsections:
- Blue
- Red

So our table of contents for that page should be:
- Shoes
- Dresses
-- Blue
-- Red
- Shorts

In this case you will be needing 5 anchor fields in our sections, corresponding to each part of the website. You can nest the categories by using the | sign. So our anchor elements will be as follows:
Shoes
Dresses
Dresses|Blue
Dresses|Red
Shorts

This will create the proper navigation for that page. Of course you can use as many other elements as you like, these are just the anchor elements.

Displaying anchors

Now we have succesfully added anchor elements, we can create the view file. The table of contents with all the anchors is available through the getAnchors() function. This function can be used in all view and layout files and will loop through all provided anchor elements on that page.

An example on how to use it would be:

<ol>
   <?php foreach($webigniter->getAnchors() as $item):?>
      <li><a  href="#<?=$item['id'];?>"><?=$item['name'];?></a></li>
      <?php if(key_exists('children', $item) && count($item['children']) > 0):?>
         <ol>
         <?php foreach($item['children'] as $child):?>
            <li><a href="#<?=$child['id'];?>"><?=$child['name'];?></a></li>
         <?php endforeach; ?>
         </ol>
      <?php endif; ?>
   <?php endforeach;?>
</ol>

 

As you can see we used a foreach to loop through the $webigniter->getAnchors() array. When there are subitems, they will be placed in a key named children. You can use an if statement to find out if there are children or not.

To place the second part of the anchor (the actual destination where the content resides) you can use:
<div id="<?=$anchor['id'];?>"><?=$anchor['name'];?></div>
Where $anchor is the name of the anchor in your view file. This creates a div with an id and the name of the anchor is shown. This results in a div which is capable of being the destination for a link in our table of contents. If you want to, you can also get the name of the parent (if present). Use $anchor['parent'] to get the parent name, if there is no parent, the value will be null.