Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Underscore / Microtemplate Replace Line Breaks - Strange Behaviour

I'm using the Underscore template (which is based on John Resig's Microtemplate) and whenever I try to replace line breaks inside of it, I get strange behaviors. For example, if I have text like this:

var message = 'Line1\r\n\r\nLine2';

I can properly replace line breaks with br tags if I do this:

$('#example1_no_template').html(message.replace(/\r?\n/g, '<br />'));

However, if I try to replace line breaks inside the Underscore template with the example code below, I don't get any br tags inserted:

<script id="template1" type="text/html">
    <%= message.replace(/\r?\n/g, '<br />') %>
</script>

<script>
var template1 = _.template($('#template1').html());
$('#example1_template').html(template1({ message: message }));
</script>

And strangely, if I change my regular expression inside the template to the following, then I get all kinds of br tags inserted all over the place:

<script id="template3" type="text/html">
    <%= message.replace(/[\r\n?]/g, '<br /><br />') %>
</script>

All of these behaviors are shown in this fiddle: http://jsfiddle.net/GHtDY/5/

Any idea what's going on? Is it possible to replace line breaks inside the template?

like image 203
Johnny Oshika Avatar asked Oct 07 '11 04:10

Johnny Oshika


1 Answers

I wonder if Underscore's template parser has a bit of a bug somewhere. If you use the RegExp object syntax instead of the regex literal syntax:

<script id="template1" type="text/html">
    <%= message.replace(new RegExp('\r?\n', 'g'), '<br />') %>
</script>

then you start getting the expected results: http://jsfiddle.net/ambiguous/GHtDY/6/

Your "funky output" example:

<%= message.replace(/[\r\n?]/g, '<br /><br />') %>

is coming out funky because Underscore is replacing the n with your <br> elements. Anyway, that character class is supposed to match any single CR, LF, or question mark and that's not what you're trying to do anyway.

I suspect that Underscore's template parser has some problems with some regex literals; you will notice that /\s/g doesn't work as expected either. In particular, it seems to have some trouble parsing escape sequences such as \r and \s inside a regex literal. For example, this:

<script id="template1" type="text/html">
    <%= message.replace(/\d/g, '<br /><br />') %>
</script>

doesn't work as expected when message contains some digits but using new RegExp

<script id="template1" type="text/html">
    <%= message.replace(new RegExp('\d', 'g'), '<br /><br />') %>
</script>

does work as expected.

like image 117
mu is too short Avatar answered Oct 18 '22 08:10

mu is too short