hello-world
webエンジニアのメモ。とりあえずやってみる。

[jade]lodash(underscore.js)のtemplate機能を使う際にテンプレート変数の記述にハマる

公開日時

lodashUnderscore.js)のtemplate機能を使うために以下のようなhtmlを作ろうとしたのですが、

<script type="text/html" id="tpl">
      <li class="hoge">
        <section class="fuga<%= id %>">
          <h3 class="title"><%= title %></h3>
          <h4 class="sub-title"><%= sub-title %></h4>
        </section>
      </li>
</script>

Jadeで上記を記述しようとした際に少しハマったのでメモを残しておきます。

最初、以下のようにすればできるんじゃないかなと思ったのですが、

script(type='text/html', id='tpl')
  li.hoge
    section.fuga<%= id %>
      h3.title <%= title %>
      h4.sub-title <%= sub-title %>

↓↓↓↓↓

<script type="text/html" id="tpl">
  <li class="hoge">
    <section class="fuga"><%= id %>
      # ↑ 本当はfuga<%= id %>というclass名にしたいのにタグが切れてしまう
      <h3 class="title"><%= title %></h3>
      <h4 class="sub-title"><%= sub-title %></h4>
    </section>
  </li>
</script>

class名へのテンプレート変数をうまく設定できず。。。

あまりキレイな解決策ではないですが、|で区切ってjade上にhtmlを記述すればテンプレート変数をclass名に使用できました。

script(type='text/html', id='tpl')
  |<li class="hoge">
  |  <section class="fuga<%= id %>">
  |    <h3 class="ctitle"><%= title %></h3>
  |    <h4 class="sub-title"><%= sub-title %></h4>
  |  </section>
  |</li>

↓↓↓↓↓

<script type="text/html" id="tpl2">
  <li class="hoge">
    <section data-id="<%= id %>" class="fuga">
      <h3 class="title"><%= title %></h3>
      <h4 class="sub-title"><%= sub-title %></h4>
    </section>
  </li>
</script>

属性値(attributes)にテンプレート変数を使う場合は、jadeの書き方で問題なく動くようです。

data-id=だと<, >がエスケープされるのでdata-id!=を指定しています。

script(type='text/html', id='tpl')
  li.hoge
    section.fuga(data-id!='<%= id %>')
      h3.title <%= title %>
      h4.sub-title <%= sub-title %>

↓↓↓↓↓

<script type="text/html" id="tpl2">
  <li class="hoge">
    <section data-id="<%= id %>" class="fuga">
      <h3 class="title"><%= title %></h3>
      <h4 class="sub-title"><%= sub-title %></h4>
    </section>
  </li>
</script>

参考