使う機会があったので、メモ。
_.templateSettingsを使うことで、構文を上書きできる。
デフォルトでは、「-」を使うとエスケープされますが、以下の例では、「-」を使った場合に、「=」と同様にエスケープされないように上書きしています。
index.html
<script id="t" type="text/template">
interpolate: <%= test %><br>
escape: <%- test %>
</script>
script.js
_.templateSettings = {
evaluate : /<[%@]([\s\S]+?)[%@]>/g,
interpolate : /<[%@][=|-]([\s\S]+?)[%@]>/g,
escape : /<[%@]_([\s\S]+?)[%@]>/g
};
var t = _.template($('#t').html());
var h = t({
test: '<b>test</b>'
});
$('body').append(h);
結果はどちらも<b>test</b>となる。
また、<% val %>の書き方が気に食わない場合も変更することができる。
以下のようにすると、{{ val }}のように記述することができます。
script.js
_.templateSettings = {
interpolate : /\{\{(.+?)\}\}/g
};