Skip to content

Instantly share code, notes, and snippets.

@multiplegeorges
Forked from kares/simpleFormat.js
Created December 20, 2012 17:32
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save multiplegeorges/4347009 to your computer and use it in GitHub Desktop.
Save multiplegeorges/4347009 to your computer and use it in GitHub Desktop.
Handlebars helper to replicate the functionality of Rails' simple_format view helper. Wraps everything in a paragraph and corrects newlines and carriage returns. Ignores all other HTML.
Handlebars.registerHelper 'simple_format', (text) ->
carriage_returns = /\r\n?/g
paragraphs = /\n\n+/g
newline = /([^\n]\n)(?=[^\n])/g
text = text.replace(carriage_returns, "\n") # \r\n and \r -> \n
text = text.replace(paragraphs, "</p>\n\n<p>") # 2+ newline -> paragraph
text = text.replace(newline, "$1<br/>") # 1 newline -> br
text = "<p>" + text + "</p>";
new Handlebars.SafeString text
@hesham
Copy link

hesham commented Nov 12, 2017

Saw this while googling for the exact same thing. Hope you're doing well, man!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment