How to strip (some) markdown markup from a tag in Statamic

Published May 18th 2018

I recently came across a site build in Statamic where I needed to have a title that could be formatted using markdown, but also needed to be used in the page's <title> tag as a fallback. This meant that there was a risk that the page title would have the asterisks used to make the text appear bold in the page tab and in search engine results. Not ideal, eh?

Luckily, Statamic comes with a nifty modifier that exposes the str_replace function of PHP within Antler templates – replace.

To quote the docs, replace:

Finds and replaces all occurrences of a string with a totally different string.

Simply add it to the tag of the content that you want to output. In my case, this was a tag called seo_title. Without modifying the content, it was outputting something like This is an **awesome** title. I wanted it to output This is an awesome title within the title tag – sans asterisks.

In my code, I also made use of the fallback functionality of Antlers. Here's the code below:

<title>{{ seo_title replace="*|" or title }} | Site Name</title>

In my replace, I'm looking for any instances of * and replacing them with null.

It's worth noting that unlike a lot of modifiers, you do not put a pipe between it and the tag name. Another thing worth noting is that the modifier is scoped to the tag it shares a condition with. So if you were to put it at the end of the tag, it would only run str_replace on the output of title, not seo_title.

Hope that helps. Any questions, drop me a comment and I'll reply ASAP!

Note: It's worth pointing out – as Erin (@emd over on Statamic's Slack group), that this won't strip all markup from a tag. To do that, you'll want to use the strip_html modifier. I'll write up a post about how to do this over this weekend and update this post.

Feel free to prod me over on the Statamic Discord if I haven't when you read this!