BorisMoore / jsrender

A lightweight, powerful and highly extensible templating engine. In the browser or on Node.js, with or without jQuery.
http://www.jsviews.com
MIT License
2.67k stars 339 forks source link

space is not html-encoded #358

Closed landall closed 4 years ago

landall commented 4 years ago

The same as #356

{{>var}} and {{html:var}} don't encoded the space to nbsp; So the browser will only render one space.

echolet commented 4 years ago

A space and a non breaking space are two different characters.

landall commented 4 years ago

A space and a non breaking space are two different characters.

Space should be encoded to & nbsp; or & ensp; , which depends on your layer requirement. but leaving it a space char is always wrong.

BorisMoore commented 4 years ago

Standard HTML encoding does not include the space character. Its purpose is to prevent HTML injection attacks, etc. See here https://stackoverflow.com/a/7382028/1054484, for example, for a discussion. (And note what they say about not converting space to nbsp.)

If you want you can create your own converter, {{htmlAndNonbreakingSpace: ...}}, in which you can first call the built-in HTML encoder: $.views.converters.html(value); and then in addition convert space characters to non-breaking space characters. Of course the effect on HTML rendering is not only to make two space characters use two space widths, but also pervent line breaks with the following word.

You can alway use <pre> if you want spaces to render without being collapsed down to single space width. Then you won't need to convert to nbsp characters...

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/pre

I'll close this issue, but you can still comment in it...

landall commented 4 years ago

Thanks, I know why. I create a converter to convert space and linebreak to html entity to keep the same look between text in a div and text in a textarea.

        $.views.converters("html2", function(html) {
            Encoder.EncodeType = "entity";
            var string = Encoder.htmlEncode(html,true).replace(/ /g, "&ensp;");
            string = string.replace(/&#13;&#10;/g,"<br/>")
            string = string.replace(/&#10;/g,"<br/>");
            return string;
        });
landall commented 4 years ago

I find it is very different between English and Chinese habits about the space. Space in Chinese not only means separate two words but also is a tool of formatting.

BorisMoore commented 4 years ago

Glad that approach worked for you...