Jump to content

Alphabetized listing


nurtsio
 Share

Recommended Posts

Hi guys,

I'm working with a page that needs a vocabulary; a list of items with only two fields (word and explanation).

I have pondered how to make this listing with alphabet titles. All words alphabetized of course. Output like this:

<h3>A</h3>
<ul>
<li><strong>absolute monarchy</strong>: explanation for absolute monarchy</li>
</ul>
<h3>B</h3>
<ul>
<li><strong>bakeapple</strong>: explanation for bakeapple</li>
<li><strong>bankster</strong>: explanation for bankster</li>
</ul>

I have all words below one parent page.

Thanks for help in advance!

Akseli

Link to comment
Share on other sites

Use your title field for the term, and another field for the definition. For the parent of all these terms, set the default sort to be by 'title' on it's children tab. Then you'd code it something like this (below). I'll use a <dl> rather than a <ul> since a <dl> would be more semantically correct here.

<?php

function listDefinitions(PageArray $children) {

    $out = '';
    $lastLetter = '';

    foreach($children as $p) {

        $letter = strtoupper(substr($p->title, 0, 1)); 

        if($letter != $lastLetter) {
            if($out) $out .= "</dl>";
            $out .= "<h3>$letter</h3><dl>";
            $lastLetter = $letter; 
        }

        $out .= "<dt>{$p->title}</dt><dd>{$p->definition}</dd>"; 
    }

    if($out) $out .= "</dl>";

    return $out;
}

echo listDefinitions($page->children); 
  • Like 2
Link to comment
Share on other sites

  • 4 years later...

I tried this code, and it worked great in a template of mine. But when I tried to use it in a hanna code, I got the an error like "cannot redeclare function". This might be rudimentary php, but I am at a loss. Any ideas on this?

Link to comment
Share on other sites

hanna code snippets are evaluated multiple times in the lifetime of a single pageview, which means the function declaration is called multiple times, which is not allowed. Try creating the function in _init.php or another file which is called only once on for each request and just execute the function in the hanna code snippet.

  • Like 2
Link to comment
Share on other sites

Just for the record, you could also wrap the function declaration with function_exists():

if (!function_exists("listDefinitions")) {
    function listDefinitions(PageArray $children) {
        // etc.
    }
}

echo listDefinitions($page->children); 
  • Like 3
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...