Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.