3

I have a field where the client can enter a URL, and then that field's value is put into the 'href' of a link in the template. The client will sometimes prepend it with "http://", sometimes with "www.", and sometimes with nothing. Unless it's prepended with "http://" or "https://", the link is interpreted as relative and tries to go to "http://mysite.com/www.otherlink.com", which is obviously not what I want.

What's the best way of automatically handling different URL formats?

6

Using Craft, you could go two ways:

  1. Make your own field-type, that handles the url in PHP and appends http:// if needed (Create a plugin for that)

  2. Check the url for 'http' in your template, and if needed prepend it:

    {% set url = entry.url | slice(0,4) == 'http' ? entry.url : 'http://' ~ entry.url %}
    

Be sure to use the {% cache %} tag if you use option 2, so the check only has to be done once.

Edit: You could use this plugin to pre-validate your urls.

| improve this answer | |
  • 2
    The {% cache %} tag is going to force a database call on every request to retrieve the cached item. It'll probably be faster to just let Twig/PHP do the processing each time. – Brad Bell Sep 15 '14 at 16:56
  • True. Didn't think about that. Don't be angry, Brad. – Paul Sep 15 '14 at 16:58
  • I'm only angry when I'm sober. – Brad Bell Sep 15 '14 at 17:27
  • That Twig template ternary totally toppled my tribulations. Thanks! – shanecavaliere Sep 15 '14 at 23:14
  • 1
    @shanecavaliere: I suggest you use the plugin, as that twig-code doesn't really validate. If your client messes up somehow, let's say miss an h at the start, the url will end up as ttp://url.com. – Fred Carlsen Sep 17 '14 at 17:25
3

There is a fieldtype called Link from Sprout that validates links, and it works very well.

One point of criticism is that the error it gives you when you haven't added the protocol isn't very client-friendly. It just says: 'Link must be a valid link.'

You could either contact Sprout and give them feedback on that, and they'll probably improve it (it's in beta), or you could modify it yourself.

| 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.