Skip to content

Instantly share code, notes, and snippets.

@JRetza
Forked from rungta/ _vanity_router.twig
Created November 27, 2018 21:51
Show Gist options
  • Save JRetza/547ae4e4502f4f05db81722c32412fed to your computer and use it in GitHub Desktop.
Save JRetza/547ae4e4502f4f05db81722c32412fed to your computer and use it in GitHub Desktop.
Vanity URL routing for Craft CMS
{# Treat the slug as a template path #}
{% set template = include(top_level_slug, ignore_missing = true) %}
{# Render the template contents if found, otherwise treat the slug as a username #}
{% if template is not empty %}
{{- template|raw -}}
{% else %}
{%- include 'users/_profile' with { username: top_level_slug } -%}
{% endif %}
{# Look for the user #}
{% set user = craft.users.username(username).first %}
{# Abort if no user was found with that username #}
{% if not user %}
{% exit 404 %}
{% endif %}
{# Render the user profile page #}
{# ... #}
<?php
/**
* Dynamic Site Routes
*/
return array(
// Existing route declarations
// ...
// Last rule because it matches all top-level URIs
'(?P<top_level_slug>[^/]+)$' => '_vanity_router',
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment