Skip to content

Instantly share code, notes, and snippets.

@mdcpepper
Created July 8, 2016 10:39
Show Gist options
  • Save mdcpepper/96baf15151576494492545ad5db7ad42 to your computer and use it in GitHub Desktop.
Save mdcpepper/96baf15151576494492545ad5db7ad42 to your computer and use it in GitHub Desktop.
Using template variables to determine a URL Format
<?php
namespace Craft;
class UrlFormatsVariable
{
// Use in the URL Format:
//
// {{ craft.urlFormats.treatments(object) }}
public function treatments($entry)
{
// Craft checks the URL format with an array `object` first, to see if there's a {slug},
// and so whether it should be checked for uniqueness and incremented if necessary.
if (!$entry || !($entry instanceof EntryModel))
{
return '{slug}';
}
$isTreatment = ($entry->type->handle === 'treatment');
$hasChildren = (bool) $entry->getChildren()->type(array('treatmentGroup', 'treatment'))->total();
// If the entry has a parent, prepend it's URI, or just 'treatments'
$parent = $entry->getParent();
$uri = ($parent) ? $parent->uri : Craft::t('treatments');
// An Entry has it's own page if it isn't a treatment, or it has content, otherwise
// it is displayed on the parent page, identified by 'path/to/parent#entry-slug'
$uri .= ($hasChildren || !$isTreatment ? '/' : '#' );
$uri .= $entry->slug;
return $uri;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment