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

Y’all got any more of them handlebars helpers?

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

handlebars

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.

Cheers! :beers:

2 Likes

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.

1 Like