LoginSignup
1
0

More than 3 years have passed since last update.

DenoでEJSをレンダリングする

Last updated at Posted at 2020-06-06

概要

Denoでビューエンジンを使用してテンプレートエンジン「EJS」をレンダリングします。
テンプレートエンジン「EJS」は、HTMLをサーバー処理するために使用します。

ディレクトリ構成

/
├──public
   ├──index.ejs
app.ts

モジュールをインポート

以下、2つのモジュールをインポートします。
・サーバーレイヤーを作成するためにoak
 https://deno.land/x/oak
・HTML(レイアウト)を提供するビューエンジン
 https://deno.land/x/view_engine

app.ts
import { Application, Router } from "https://deno.land/x/oak/mod.ts";
import { viewEngine, engineFactory, adapterFactory } from "https://deno.land/x/view_engine/mod.ts";

ポートをリッスンするためにApplicationクラスとルートレイヤーを提供するためにRouterをインポートしています。

アプリケーションの初期化

インポート後にApplicationRouterを初期化します。

app.ts
const app = new Application();
const router = new Router();

アプリケーションを初期化した後、ビューエンジンを使用するようにアプリケーションを構成します。

app.ts
const ejsEngine = await engineFactory.getEjsEngine();
const oakAdapter = await adapterFactory.getOakAdapter();

 

ビューエンジンのボイラープレート(定型書式)の準備ができましたら、
次のコードでビューエンジンをミドルウェアとしてアプリケーションに渡します。

app.ts
app.use(viewEngine(oakAdapter, ejsEngine));

ルート作成

次にルートを作成します。
レンダリングするejsファイルを指定して、任意のdataを渡す設定をします。

app.ts
router.get('/', (ctx: any) => {
  ctx.render('./public/index.ejs', { data: { message: 'Hello' } })
});

ルーターを必要とするミドルウェアを追加します。

app.ts
app.use(router.routes());
app.use(router.allowedMethods());

アプリケーションを提供

これでapp.tsファイルが完成したので、
リッスンしてアプリケーションを提供します。

app.ts
console.log('http://localhost:8000/');
await app.listen({ port: 8000 });

 

完成イメージ

app.ts
import { Application, Router } from 'https://deno.land/x/oak/mod.ts';
import { viewEngine, engineFactory, adapterFactory } from 'https://deno.land/x/view_engine/mod.ts';

const app = new Application();
const router = new Router();

const ejsEngine = await engineFactory.getEjsEngine();
const oakAdapter = await adapterFactory.getOakAdapter();

app.use(viewEngine(oakAdapter, ejsEngine));

router.get('/', (ctx: any) => {
  ctx.render('./public/index.ejs', { data: { message: 'Hello' } })
});

app.use(router.routes());
app.use(router.allowedMethods());

console.log('http://localhost:8000/');
await app.listen({ port: 8000 });

EJS構文のHTMLタグ追加

最後に次のようにEJS構文のHTMLタグを追加します。
そうすることで、app.tsから渡されたmessageを受け取ることができます。

index.ejs
<!DOCTYPE html>
<html lang="ja">
    <head>
        <meta charset="UTF-8">
    </head>
    <body>
        <p><%= data.message %></p>
    </body>
</html>

 

動作確認

次のコマンドを実行します。

$ deno run --allow-net --allow-read app.ts

以下にアクセスしてHelloと表示されればOKです。
http://localhost:8000/

1
0
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
0