I am using a phone number in a global variable called {{ global.phone }} with the format "(555) 555-5555". I'd like to use that same variable/string and remove spaces, dash, and parenthesis to use for the href tel link. I've tried a few different things from Twig and Craft documentation, but nothing is working. Here's what I have right now.

<p>Ph: <a href="tel:{{ global.phone|trim(' ') }}">{{ global.phone }}</a><br/>

Is this possible to do? If so any advise how to accomplish this?


I haven't tried this but I think that you can use the twig replace function. Something like:

{{ global.phone|replace({"(":"", ")":"", "-":"", " ":""}) }}

Update In your case, since the prefix (1-) is required, and "-" are allowable, the replace string for "(555) 555-5555" would be:

{{ global.phone|replace({"(" : "1-", ") " : "-"}) }}
| improve this answer | |
  • Works great, however got an error with double pipe. Left one in code and it works no problem. Thank you! – frshjb373 Nov 12 '14 at 16:45
  • I fixed that. Sorry about that. – Douglas McDonald Nov 12 '14 at 16:45
  • I'm glad it works. Which reminds me... I need to do that for a project I'm working on. So thanks! ;) – Douglas McDonald Nov 12 '14 at 16:47
  • fyi... i think that the phone number needs to include the prefix (1-) and dashes are allowable (i.e. 1-555-555-5555). So you may need to prefix that number as well. – Douglas McDonald Nov 12 '14 at 16:52
  • I'll use the latter, but looking at documentation and recommendations around web, not seeing a clear rule to use (1-) prefix or not. Same goes for including dashes or not. I've always done only numbers disregarding prefix and that's always worked for me. – frshjb373 Nov 12 '14 at 17:04

For what it's worth, you can strip out all non-numerics with this something like this:

{{ globalPhoneNumber.phoneNumber|replace('/[^0-9]/', '') }}

Or, as part of a tel: anchor:

<a href="tel:{{ globalPhoneNumber.phoneNumber|replace('/[^0-9]/', '') }}">{{ globalPhoneNumber.phoneNumber }}</a>
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.