For a project I’ve been working on recently I needed to convert text, retrieved from an API, to HTML.
The text isn’t “mark-down” but does contain line-breaks, URLs, hash-tags etc. etc. Since there wasn’t any add-on or snippet doing exactly this, I decided to roll my own.
Now I want to share my ‘snippet’ (only one file) with you, so you hopefully can benefit from it too, or modify it if needed.
As you can see I’ve included my test-file as well. Download both files and place “text-2-html.js” into your “app/helpers” directory (and “text-2-html-test.js” into your “tests/units/helpers” directory).
Now you can use the helper like this:
By default the helper converts:
When configured it also converts:
Here are some examples to illustrate these options:
I must tell that the phone-number feature might act a bit buggy (that’s why it’s not a default feature); it does recognize must phone-number formats but also other numbers, intended for something else. Try and see if it works for your purposes, otherwise I might work on that one day.
Assume we have the following text:
With this in your Handlebars:
Would result in the following HTML-output:
How're ya doin'?<br>
Sorry you can't get through.<br>
Why don't you leave me your name, mine is <a href=”https://www.twitter.com/planetcrypton” target=”_system”>@planetcrypton</a>, and your number, mine is <a href=”tel:+4560632840″>+4560632840</a>, and I'll get back to you.<br>
Don't forget to visit <a href=”http://www.wearedelasoul.com/” target=”_system”>http://www.wearedelasoul.com/</a><br>
Mail me at <a href=”mailto:email@example.com”>firstname.lastname@example.org</a> <a href=”https://www.twitter.com/hashtag/oldschool” target=”_system”>#oldschool</a> <a href=”https://www.twitter.com/hashtag/plug1″ target=”_system”>#plug1</a> <a href=”https://www.twitter.com/hashtag/plug2″ target=”_system”>#plug2</a> <a href=”https://www.twitter.com/hashtag/plug3″ target=”_system”>#plug3</a>
Here’s a documentation of the available attributes, so you can go ahead and use it:
|Attr. name||Type||Default value||Note|
|phone||boolean||false||convert phone-numbers, might be buggy|
|target||string||_blank||define target for all links|
|hashTagURLPrefix||string||null||convert hash-tags and define the URL-prefix|
|mentionURLPrefix||string||null||convert mentions and define the URL-prefix|
|mentionAtShown||boolean||true||show / hide the @-sign for mentions|