How to format carriage returns in a Backbone model in a Mustache template

余生颓废 提交于 2020-01-16 09:41:34

问题


I'm using Backbone models as input into Mustache templates to generate HTML.

I have a Backbone model with a number of attributes, such as name, description and id. The description attribute can contain carriage returns, which I want to render as <br> tags when they're rendered in the template.

By default, Mustache simply outputs the carriage returns directly, so the markup looks tidy, but the rendered result has no breaks.

I don't particularly want to replace \n\r in the description attribute, as that property could be used elsewhere (e.g. in alt or meta tags).

The only idea I have so far is to add a duplicate description attribute that has the formatted text.

Is there nothing in Mustache that formats HTML line breaks as <br> tags?


回答1:


Mustache is very limited on purpose. If you need anything special in a Mustache template, you prepare your data in JavaScript so that Mustache's interpolation and loops can handle it. In your case, that means splitting your string on EOLs to get an array:

// Adjust the regex to suit your data, this one is pretty loose.
var lines = string.split(/[\r\n]+/)
                  .map(function(line) { return { line: line } });

and then loop over that array in Mustache:

{{#lines}}
    {{line}}<br>
{{/lines}}



回答2:


mu is too short's answer is correct. I just want to add that the .map function isn't supported in IE8 (and older).

I ended up using a loop to achieve the same affect as we need to support IE8:

var descriptionArray = description.split(/[\r\n]+/);
var descriptionLines = new Array();
for (var line = 0; line < descriptionArray.length; line++) {
    descriptionLines.push({ Line: descriptionArray[line] });
}


来源:https://stackoverflow.com/questions/19984845/how-to-format-carriage-returns-in-a-backbone-model-in-a-mustache-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!