Skip to content

Instantly share code, notes, and snippets.

@treetop1500
Last active November 8, 2016 18:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save treetop1500/b7cdd8352aea49cd8c1c27473335b069 to your computer and use it in GitHub Desktop.
Save treetop1500/b7cdd8352aea49cd8c1c27473335b069 to your computer and use it in GitHub Desktop.
Accessible Symfony Breadcrumbs
// app/resources/views/breadcrumbs.html.twig
// this file will be included with the 'breadcrumbs' variable
<nav aria-label="You are here:" role="navigation">
<ul class="breadcrumbs">
<li>
<a href="/">
<i class="fa fa-home"></i>
</a>
</li>
{% for crumb in breadcrumbs %}
<li class="{{ crumb.class }}">
{% if 'disabled' not in crumb.class and not loop.last%}
<a href="{{ crumb.path }}">
{% endif %}
{% if loop.last %}
<span class="show-for-sr">Current: </span>
{% endif %}
{{ crumb.label }}
{% if 'disabled' not in crumb.class and not loop.last %}
</a>
{% endif %}
</li>
{% endfor %}
</ul>
</nav>
// CONTROLLER EXAMPLES
/* simple controller action with two-deep breadcrumb */
public function productAction()
{
// get a product object
$em = $this->getDoctrine()->getManager();
$products = $em->getRepository('CommonContentBundle:Product')->findAll();
// build the breadcrumbs array
$breadcrumbs = array(
array(
'label' => $product->getCategory()->getTitle(),
'path' => $this->generateUrl('product_category',array('slug'=>$product->getCategory()->getSlug())),
'class' => null
),
array(
'label' => $product->getTitle(),
'path' => $this->generateUrl('product_detail',array('slug'=>$product-getSlug())),
'class' => null
)
);
// an additional piece here can be used to create a conditional parent crumb for self referencing associations (parent/child)
if ($product->getParent()) {
$parentArray = array(
'label' => $product->getParent()->getTitle(),
'path' => $this->generateUrl('product_detail', array('slug'=>$product->getParent()->getSlug())),
'class' => 'parent'
)
array_splice($breadcrumbs, 1, 0, $parentArray);
}
return $this->render('::product.html.twig', array(
'breadcrumbs' => $breadcrumbs,
'product' => $product
));
}
// product.html.twig
{% if breadcrumbs is defined %}
{% block breadcrumbs %}
{% include "::breadcrumbs.html.twig" with breadcrumbs %}
{% endblock %}
{% endif %}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment