Does handlebars.js replace newline characters with
?

前端 未结 6 2133
星月不相逢
星月不相逢 2020-12-24 11:45

Trying to use handlebars.js for templating but the library seems to ignore newlines.

What is the correct way to deal with newlines? Should they be replaced manually

6条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-24 11:52

    Here are two approaches I prefer over the currently-accepted answer:

    1. Use white-space: pre-wrap; or white-space: pre; on the element where you want to preserve line-breaks (allowing or suppressing natural line wrapping respectively). If you want sequences of whitespace to be collapsed, which is how text in HTML is normally presented, use white-space: pre-line; but note that IE8 and below do not support this. https://developer.mozilla.org/en-US/docs/Web/CSS/white-space
    2. Or here's a version of the template helper that doesn't require any copying and pasting of external code:

      Template.registerHelper('breaklines', function (text) {
        text = Blaze._escape(text);
        text = text.replace(/(\r\n|\n|\r)/gm, '
      '); return new Spacebars.SafeString(text); });

      See https://github.com/meteor/meteor/blob/devel/packages/blaze/preamble.js for Blaze._escape

提交回复
热议问题