Mustafa Alammar
Mustafa Alammar

Reputation: 656

Multi line Underscore Template and _.each

I'm getting an error when trying to parse an underscore template this is stored as a multi-line string:

{{ _.each(records, function(record, index) { }}\
    <tr>\
        {{ record.get("hours") }}\
    </tr>\
{{ }) }}\

The error:

Uncaught SyntaxError: Unexpected token )

On line 1 (the _.each line).

The syntax looks correct to me according to underscore's docs.

Edit: I should note that i'm using {{ instead of <%= in my templates and that changing back to <%= doesn't fix the issue.

Edit: Here's the regex I use for evaluation:

// Underscore templates should use {{ variable_name }} instead of <%= variable_name =%>
_.templateSettings = {
    interpolate: /\{\{(.+?)\}\}/g
};

Upvotes: 3

Views: 2483

Answers (1)

Jack
Jack

Reputation: 11003

You need to use {[, for evaluation.

Assuming that you first defined a regex to change the default symbols that underscore.js uses for evaluating, for example

 _.templateSettings = {
       evaluate: /\{\[([\s\S]+?)\]\}/g,
       interpolate: /\{\{([\s\S]+?)\}\}/g, 
       escape: /\{\{-([\s\S]+?)\}\}/g
 };

You can then do something like

{[ _.each(records, function(record, index) { ]}
    <tr>
        {{ record.get("hours") }}
    </tr>
{[ },this); ]}

Upvotes: 4

Related Questions