EJSで使う構文まとめ

会社でGulpでEJS触わる機会が多いので、よく使う構文をまとめておこうと思います。

f:id:jotaki:20191108143317p:plain

基本

.html

<% var ejsRoot = './'; %>
<%- include(ejsRoot + '_module/ejsFileName'); %>

.ejs

<!-- .htmlで出力するHTML -->

パラメータ指定

ボタンのコンポーネントをejs化するサンプル

.html

<%- include(ejsRoot + '_module/component/button', {
  buttonColor: 'red',
  buttonLink: '/path/',
  buttonText: 'ボタンのテキスト'
}); %>

.ejs

<p class="button button--<%= buttonColor %>">
  <a href="<%= buttonLink %>">
    <%= buttonText %>
  </a>
</p>

.html側でパラメータ指定がない場合はGulpでコンパイルエラーになるのを回避するには、

<% if( typeof buttonColor!='undefined' ){ %>
  <!-- ここに `buttonColor: 'hogehoge' が定義されている場合 -->
<% } else { %>
  <!-- それ以外の場合 -->
<% } %>

などとすると分岐してエラー回避できる。

参考: Using "if" to check variable before usage results in Error, Undefined · Issue #90 · tj/ejs

出力するバナーの個数をパラメータで指定する

.html

<%- include(ejsRoot + '_module/component/banner', { item: 4 }); %>

.ejs

<ul>
  <% for (var i=0; i<item; i++) { %>
    <li>
      <a href="#">
        <img src="banner.png" alt="">
      </a>
    </li>
  <% } %>
</ul>

パンくずをパラメータで指定する

<%- include(ejsRoot + '_module/component/breadcrumb', {
  navigationList: [
    {
      path: '/',
      label: 'ホーム'
    },
    {
      path: '/parent/',
      label: '親階層ページ'
    },
    {
      path: '',
      label: '子階層ページ'
    }
  ]
}); %>

.ejs

<ol>
  <% for (var key in navigationList) { %>
  <%
    // .html 側に定義された path と label をループしてパンくずを生成
    var path = navigationList[key].path;
    var label = navigationList[key].label;
  %>
  <li>
    <% if ( path === '' ) { %>
      <span class="current">
        <%= label %>
      </span>
    <% } else { %>
      <a href="<%= path %>">
        <%= label %>
      </a>
    <% } %>
  </li>
  <% } %>
</ol>

参考: テンプレートエンジンEJSで使える便利な構文まとめ - Qiita