Skip to content

Instantly share code, notes, and snippets.

@piotrpog
Last active March 4, 2019 14:26
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save piotrpog/19592c69ad500090538acbb8244ea891 to your computer and use it in GitHub Desktop.
Save piotrpog/19592c69ad500090538acbb8244ea891 to your computer and use it in GitHub Desktop.
This macro fetches routes into Twig template. More info on http://craftsnippets.com/articles/url-macro
{# v2 #}
{% macro url(routeName, tokens) %}
{% spaceless %}
{% set keyword = 'name' %}
{% set routeString = null %}
{% for route, routeSettings in craft.app.routes.getConfigFileRoutes %}
{% if routeSettings[keyword] is defined and routeSettings[keyword] == routeName %}
{% set routeString = route %}
{% endif %}
{% endfor %}
{% if routeString and tokens is not empty %}
{% set routes = routeString|split('/') %}
{% set tokenIndex = 0 %}
{% set resultArray = [] %}
{% for value in routes %}
{% if value matches '/\\<[\\w]+\\>/' %}
{% if tokens is iterable %}
{% set value = tokens[tokenIndex] %}
{% set tokenIndex = tokenIndex + 1 %}
{% else %}
{% set value = tokens %}
{% endif %}
{% endif %}
{% set resultArray = resultArray|merge([value]) %}
{% endfor %}
{% set result = resultArray|join('/') %}
{{url(result)}}
{% endif %}
{% endspaceless %}
{% endmacro %}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment