Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Using Perch to create an alphabet of links for a collection or list/detail page.
<main role="main" class="glossary">
<div class="group">
<?php
// setup alphabet array for navigation
// make array of letters in span tags
$nav_arr = array(
'0-9' => '<span>0-9</span>'
);
for ($i = 65; $i <= 90; $i++) {
$nav_arr[chr($i)] = '<span>'.chr($i).'</span>';
}
// Go through content, if an item title begins with a letter, make it into a link instead of a span.
$current_letter = '';
perch_content_custom('Glossary', [
'skip-template' => true,
'raw' => true,
'sort' => 'title',
'sort-order' => 'ASC',
'each' => function($item) {
$word = strtoupper($item['title']);
// if the first letter of the title is different to current_letter, it's new so add it to nav_arr
if (strcmp($word[0], $GLOBALS['current_letter']) !== 0) {
$my_letter = $GLOBALS['current_letter'] = is_numeric($word[0]) ? '0-9' : $word[0];
$GLOBALS['nav_arr'][$my_letter] = '<a href="#glossary-'.$my_letter.'">'.$my_letter.'</a>';
}
return $item;
}
]);
?>
<div class="glossary-nav">
<?php
// Display our alphabet
foreach ($nav_arr as $key => $value) {
echo $value;
}
?>
</div>
<hr>
<?php
//reset $current_letter and display glossary, adding heading letters as required
$current_letter = '';
perch_content_custom('Glossary', [
'template' => 'glossary_listing.html',
'sort' => 'title',
'sort-order' => 'ASC',
'each' => function($item) {
$word = strtoupper($item['title']);
// if the first letter of the title is different to current_letter, it's new so add it to the template
if (strcmp($word[0], $GLOBALS['current_letter']) !== 0) {
$item['letter'] = $GLOBALS['current_letter'] = is_numeric($word[0]) ? '0-9' : $word[0];
}
return $item;
}
]);
?>
</div>
</main>
<perch:before><div class="group"></perch:before>
<perch:if exists="letter">
<perch:if exists="perch_item_first"><perch:else /><a href="#top" class="glossary__top">Go to top</a></div><div class="group"></perch:if>
<div class="glossary__letter">
<h2 id="glossary-<perch:content id="letter" />"><perch:content id="letter" /></h2>
</div>
</perch:if>
<div id="<perch:content id="slug" type="slug" for="title" />" class="glossary__item">
<div class="glossary__term"><perch:content id="title" /></div>
<div class="glossary__meaning"><perch:content id="desc" type="textarea" /></div>
</div>
<perch:after><a href="#top" class="glossary__top">Go to top</a></div></perch:after>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment