Skip to content

Instantly share code, notes, and snippets.

@rungta
Last active March 14, 2019 09:21
Show Gist options
  • Save rungta/8a9e3dd48d77be20948751c05f1de0ea to your computer and use it in GitHub Desktop.
Save rungta/8a9e3dd48d77be20948751c05f1de0ea 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).one() %}
{# 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 [
// Existing route declarations
// ...
// Last rule because it matches all top-level URIs
'<top_level_slug:{slug}>' => [ 'template' => '_vanity_router' ],
];
@rungta
Copy link
Author

rungta commented Mar 14, 2019

Updated for Craft 3. See Craft 2 version.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment