LoginSignup
1
2

More than 1 year has passed since last update.

Node + Denoで使えるテンプレートエンジンEta(イータ)

Last updated at Posted at 2022-09-10

はじめに

良さそうなnode.js向けレンダリングエンジンを見つけたので紹介させてください。
Etaと言います。node.jsでの利用のほか、CDNでの利用、Denoでの利用が可能のようです。
jsでの軽量単体アプリケーションフレームワーク(Neutralino)での使用も可能でした
いづれDenoに乗り換える際サーバサイドレンダリングのロジック部分をそのまま使おうという魂胆で使ってみました。
軽量で高速に動作するようです。Fastifyでメモリ上にバッファすればさらに最強と見てます。
ect最強と思ってましたがこれもいいかもです。ちなみにectとは無関係のようです。

読み方はイータになります。
アルファ・ベータ・デルタ・シータ・イータのイータです
Etaユーザが増えた際イーティーエー等誤った読み方が定着することを全力で阻止するための投稿になります。
以上。

おまけ

今回小さなアプリケーションを作って試した際の知見を残しておきたいと思います。
node:v16.13.0
eta:v1.12.3

レンダリング実行

logic.js
let template = "<div><%= it.title %></div>";
let htmlString = Eta.render(template ,{ title: 'タイトル' ,type: 'integer' ,name: '名前' });

値の表示

template.eta
<%= it.name %>

jsの実行

template.eta
<% console.log("ログ"); %>

条件分岐

template.eta
<% if (it.type == 'integer') { %>
    <%= it.name %>?:number;
<% } %>
<% else if (it.type == 'object') { %>
    <%= it.name %>?:Object;
<% } %>
<% else { %>
    <%= it.name %>?:<%= it.type %>;
<% } %>

反復

<% %>内にjs書けるってことです

array

template.eta
<% users.forEach(function(user){ %>
  <%= user.first %> <%= user.last %>
<% }) %>

object

template.eta
<% Object.keys(someObject).forEach(function(prop) { %>
  <%= someObject[prop] %>
<% }) %>

インクルード

template.eta
<%~ include(name, options) %>
<%~ includeFile(path, options) %>

ホントは読み方はどうでもよくむしろここからが本題

他のテンプレートエンジン使った人なら予想がつくかもしれませんが、公式サイトやstackoverflowにもなく、ちょと悩んだので備忘録です

テンプレート内で関数実行

今回Sugarと言うユーティリティ系のライブラリを使ってキャメルケースに変換します

logic.js
let entitySrc = Eta.render(entityFile ,{ name:"class_name"  ,camelize :Sugar.String.camelize });
template.eta
<%= it.camelize(it.name) %>;

テンプレートを再帰的にレンダリング

logic.js
let self = "<% names.forEach(function(name){ %> <%= name.first %> <%= name.last %> <%~ Eta.render( it.self, { names: it.names.arr ,self: it.self  }) %> <% }) %>";
let htmlString = Eta.render(self ,{ 'names': array ,'self': self });

※ちょっと良くない例になってしまったのですがnamesが内部にさらにarrayを持っている想定です。雰囲気で理解
it.selfにテンプレート文字列を渡してtenplate内でもう一回render関数を呼んでます
以下の部分でリカーシブ

js内の再帰呼び出し部分
<%~ Eta.render( it.self, { arr: it.names.arr ,self: it.self  }) %>
1
2
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
1
2