Handlebars helper to break text strings into paragraphs at `\n` in a JSON file?


#1

Y’all got any more of them handlebars helpers?

Maybe one that can break strings into paragraphs at \n in a JSON file?

handlebars


#2

For you kids following along at home, this is the answer.

import { helper } from "@ember/component/helper";
import { htmlSafe } from "@ember/template";

export function breakLines([str]) {
  let div = document.createElement("div");
  str.split("\n").forEach(str => {
    div.appendChild(document.createTextNode(str));
    div.appendChild(document.createElement("br"));
    div.appendChild(document.createElement("br"));
  });
  return htmlSafe(div.innerHTML);
}

export default helper(breakLines);

Along with the following in your template.

{{breakLines def.definition}}

And the Twiddle example this was extracted from for anyone Googling for answers.

https://ember-twiddle.com/8dbe124b7f716f16bc2c011597dd1e85

Cheers! :beers:


#3

I think you can also just return div instead of return htmlSafe(div.innerHTML).

Helpers often returns strings, but they can also return DOM Nodes directly.