{{craftSnippets}}
Home Articles Plugins Starter theme About
  • Home
  • Articles
  • Converting email addresses into links using Twig macro
Posted on Apr 25, 2019 by Piotr Pogorzelski

Converting email addresses into links using Twig macro

Learn how to turn email addresses in text into "mailto" links that are secured from email harvesting spam bots.

This macro is useful for keeping your static translations HTML-free. If you have some email addresses in text, you don't need to manually wrap them in <a> tags - macro will do it for you, using regular expression.

As a bonus, it will also make these addresses hidden from spambots by replacing @ in address with corresponding HTML entity - &#64;. Such address is rendered by browser exactly the same way as regular one and is fully usable. Spambots however, might have problems with recognizing it as email address and ignore it. Well, at least these dumber ones that don't render HTML, but just scan trough website source code.

Here's macro code. You can test it out using interactive demo.

{% macro emailLinks(text, class) %}
{% spaceless %}
{% set text = text|replace('/([a-zA-Z0-9_.+-]+)+@([a-zA-Z0-9-]+.[a-zA-Z]+)/', '<a ' ~ (class ? 'class="' ~ class ~ '" ') ~ 'href="mailto:'~ '\\1&#64;\\2' ~'">'~ '\\1&#64;\\2' ~'</a>') %}
{{text|raw}}
{% endspaceless %}
{% endmacro %}

Macro accepts two parameters:

  • text that will be parsed.
  • class - optional parameter that can be used to add class to links.

Further reading #

  • https://www.pinnacledisplays.com/unicode-converter.htm - protecting email addresses from spambots using various techniques.

TAGS:
#Craft CMS 3 #Twig macro
Quick links for this article:
Email links macro on github gists
Let the expert handle
your Craft CMS project.
70 Basic icons by Xicons.co
piotrpog@protonmail.com
Copyright © 2026 Piotr Pogorzelski
piotrpog@protonmail.com      LinkedIn profile      Github profile