Help us understand the problem. What is going on with this article?

lodash.js (underscore.js)でのtemplateの使い方

More than 3 years have passed since last update.

要件

例)フロントエンドでajaxで取ってきたデータに応じて下記テーブルに要素の追加を行いたいなぁって時、、、

ìndex.html
<table id="userInfo">
    <tr>
        <td>名前</td>
        <td>性別</td>
        <td>職業</td>
    </tr>
</table>

jQueryだけでやると

script.js
$.ajax({
  url: ajaxurl,
  type: "GET",
  timeout: 10000
}).done(function(result, textStatus, xhr) {
  for (var i = 0; i < result.length; i++) {
    var $tr = $("<tr></tr>");
    $tr.append("<td>" + result[i].name + "</td>")
        .append("<td>" + result[i].gender + "</td>")
        .append("<td>" + result[i].job + "</td>");
    $("#userInfo").append($tr)
  }
}).fail(function(xhr, textStatus, error) {
  console.log("error");
});

こんなんかな?(もうちょっとマシなやり方あると思いますが)

問題点

htmlをどう書くかがjavascript内に記載してあるのちょっと生理的に受け付けない

ってことでtemplateを使うと
htmlはhtml内に書けるのですっきりします

templateの使い方

まずはhtmlにtemplateを追記しましょう

index.html
<script type="text/html" id="lodashTemplate_userData">
  <tr>
      <td><%= name %></td>
      <td><%= gender %></td>
      <td><%= job %></td>
  </tr>
</script>

javascriptも結構すっきり

_.template にhtml内のテンプレートを記載した部分を入れてテンプレを作成したら、あとは対応するデータを入力すると対応したhtmlを吐き出してくれます。

script.js
$.ajax({
  url: ajaxurl,
  type: "GET",
  timeout: 10000
}).done(function(result, textStatus, xhr) {
  var compiled = _.template($("#lodashTemplate_userData").html());
  for (var i = 0; i < result.length; i++) {
    $("#userInfo").append(
      compiled({
        "name": result[i].name,
        "gender": result[i].gender,
        "job": result[i].job,
      }));
  }
}).fail(function(xhr, textStatus, error) {
  console.log("error");
});

※lodashを読むのを忘れないように

まとめ

これでjavascriptがhtmlに汚染されずにすむような気がします:innocent:

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away