LoginSignup
0
1

More than 5 years have passed since last update.

【underscore.js】テンプレート構文の上書き

Posted at

使う機会があったので、メモ。
_.templateSettingsを使うことで、構文を上書きできる。
デフォルトでは、「-」を使うとエスケープされますが、以下の例では、「-」を使った場合に、「=」と同様にエスケープされないように上書きしています。

underscorejs/template

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: '&lt;b&gt;test&lt;/b&gt;'
});

$('body').append(h);

結果はどちらも<b>test</b>となる。
また、<% val %>の書き方が気に食わない場合も変更することができる。
以下のようにすると、{{ val }}のように記述することができます。

script.js
_.templateSettings = {
    interpolate : /\{\{(.+?)\}\}/g
};
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1