Skip to content

Instantly share code, notes, and snippets.

@olets
Last active September 9, 2019 14:38
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save olets/a835d4f8df5028fb30649d6a8aa03de2 to your computer and use it in GitHub Desktop.
Save olets/a835d4f8df5028fb30649d6a8aa03de2 to your computer and use it in GitHub Desktop.
get the domain from a url
{% set no_protocol = url|split('//')[1] ?: url %}
{% set only_domains = no_protocol|split('/')[0] ?: no_protocol %}
{% set url_domain = '' %}
{% if only_domains|split('.')[2] %}
{% set url_domain = only_domains|split('.')[1] %}
{% else %}
{% set url_domain = only_domains|split('.')[0] %}
{% endif %}
@toomanyredirects
Copy link

toomanyredirects commented Sep 9, 2019

@olets Nice try, but...
Your function will throw an error if no sub domain is part of the URL string.

Instead, try this one:

{# Twig URL parser: #}
{% set url= 'http://subdomain.domain.tld/some/dir/file.pdf' %}
{% set noprotocol = url|split('//')[1] ?: url %}
{% set domains = noprotocol|split('/')[0] ?: noprotocol %}
{% if domains|split('.')[2] is defined %}
   {% set subdomain = domains|split('.')[0] %}
   {% set domain = domains|split('.')[1] %}
   {% set tld = domains|split('.')[2] %}
{% else %}
   {% set subdomain = '' %}
   {% set domain = domains|split('.')[0] %}
   {% set tld = domains|split('.')[1] %}
{% endif %}
{% set path = noprotocol|replace({(subdomain ? subdomain ~ '.' : '') ~ (domain) ~'.' ~ (tld) :''})%}

{{ domains }}
{{ domain }}
{{ subdomain }}
{{ tld }}
{{ path }}

Always test your code before publishing: https://twigfiddle.com/phdhbi

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