LoginSignup
10
7

More than 5 years have passed since last update.

初心者が学ぶ TypeScript 入門 Ver.0.5 【準備編】

Posted at

前回のあらすじ

TypeScript入門 Ver.0.2

TypeScriptを扱うにあたって、node.jsを一度勉強してみる事にした。

  • Hello World
  • URL ルーティング
  • HTMLファイルの読込

node.js の勉強

  • 3. テンプレートエンジンを使用してみる。

まずは、テンプレートエンジンを読み込みます。

$ npm install ejs

次に ejs のテンプレートファイルを作成します。 これは ~~.ejs というようなファイル形式で作成します。

テンプレートの展開形式として今回は二種類を使います。

  • <%= 値 %>
    中にあるJS変数の値をエスケープして展開する記述方式です。
    <や>がエスケープされて出力されるので、HTMLタグを扱う場合は下の方式を使用します。

  • <%- 値 %>
    中にあるJS変数の値をエスケープしないで展開する記述方式です。
    JS変数がHTMLの場合はこちらを使いますがスクリプトインジェクションには注意して使用します。

sample.ejs
<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <title>サンプル ejs</title>
</head>
<body>

<h1><%= title %></h1>

<%- content %>

<p>ランダム生成された値は <%= randomNumber %> です。</p>

</body>
</html>

続いて server.js 側も sample.ejsに値を渡すように書き換えてみます。

server.js

const http      = require('http');
const ejs       = require('ejs');
const filSystem = require('fs');
const server    = http.createServer();

let message  = '';
// テンプレートファイルを扱う.
let template = filSystem.readFileSync(__dirname + '/sample.ejs', 'utf-8');

let randomNumber = 0;

server.on('request', function(request, response) {
    randomNumber = Math.round(Math.random() * 100);

    let data = ejs.render(template, {
        title: 'Hello Hello',
        content: "<h2>アクセスありがとうございます!</h2>",
        randomNumber: randomNumber,
    });

    response.writeHead(200, {'Content-Type' : 'text/html'});
    response.write(data);
    response.end();
});

server.listen(3000);

$ node server.js

http://localhost:3000 とブラウザでアクセスすることで ejsのテンプレートにて変数が展開されて ページが表示される。

スクリーンショット 2018-06-06 0.00.52.png

まとめ

ひとまず、こんなもんで node.jsはOkかな。

TypeScript書いてみよー!

宣伝

転職をきっかけにいろいろな試みをやってます。

ほぼ日AWS

ほぼ日AWS

AWSの各ソリューションについて 「このソリューションはどういうもの?」 って観点でまとめてみたものです。

もくもく独書 for Swift実践入門

もくもく独書 for Swift実践入門

Swift実践入門の書籍を毎日読みながら必要に応じてコードを書いてまとめていっているものです。

10
7
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
10
7