Extracting Domain Name from Links in Hugo

blog image

When working with Hugo—a popular static site generator—it’s not uncommon to need tailored solutions for specific challenges, such as extracting domain names from links. This capability can be particularly useful in e-commerce settings where clarity on payment gateways is crucial.

The Challenge:

Consider a scenario where you have a website selling products or services, and for each item, there might be multiple payment options. For user transparency, you want to indicate clearly which payment platform each link directs to:

  • Buy Now! (Stripe)
  • Buy Now! (Paypal)

Your markdown setup might look something like this:

 - https://pages.stripe.com/some_inner_page
 - https://paypal.com/some_payment_page

To address this, let’s leverage Hugo’s templating system.

Step-by-Step Implementation:

1. Creating the Domain Extraction Partial:

Navigate to the layouts/partials directory and establish a new file named extractDomain.html. Insert the following code:

{{- $link := . -}}
{{- with $link -}}
    {{- $parsedURL := urls.Parse . -}}
    {{- with $parsedURL -}}
        {{- $host := .Host -}}
        {{- $domainParts := split $host "." -}}
        {{- index $domainParts 1 -}}
    {{- else -}}
        {{- "Unknown" -}}
    {{- end -}}
{{- else -}}
    {{- "No Link Provided" -}}
{{- end -}}

2. Embed the Extracted Domain Name into Buy Buttons:

At the desired location for your buy buttons, employ the following:

{{ range .Params.sellLink }}
<a href="{{ . }}" class="buy-button">Buy Now! ({{ partial "extractDomain.html" . | title }})</a>
{{ end }}

Here, we iterate over each sellLink, generate a button, and incorporate the extracted domain name. The | title function transforms names like “stripe” to “Stripe”.

Wrapping Up:

With Hugo’s flexible templating engine, even seemingly intricate tasks like extracting domain names from URLs become manageable. By embedding these names into buy buttons, you enhance user clarity and trust, ensuring they are always informed about their choices.

Liked this story? Share it with someone who needs to see it 👇