JavaScriptは、近い将来ますます人気が高まっており、予期しない新しい用途が見つかっています。 したがって、この傾向は私を追い越しませんでしたので、私がただ一つのプロジェクトを開発したとき、私は抵抗することができず、サーバー(Node.JS)、Webクライアント(Backbone.js-すべてが深刻です:))でJSを使用しようと決めましたモバイルアプリケーション(PhoneGap)。 私にとっての次のステップは、テンプレートエンジンの選択であり、ノードとブラウザの両方のサポートが必須でした。 それ以前は、主にDjango Template Languageを扱っていたため、選択はSwigに委ねられました。
Swigの機能:
ノードのクイックスタート
設置
npm install swig
テンプレートを作成
<h1>{{ pagename|title }}</h1> <ul> {% for author in authors %} <li{% if loop.first%} class="first"{% endif %}> {{ author }} </li> {% else %} <li>There are no authors.</li> {% endfor %} </ul>
レンダリング
var template = require('swig'); var tmpl = template.compileFile('/path/to/template.html'); tmpl.render({ pagename: 'awesome people', authors: ['Paul', 'Jim', 'Jane'] });
結果
<h1>Awesome People</h1> <ul> <li class="first">Paul</li> <li>Jim</li> <li>Jane</li> </ul>
ブラウザで
ブラウザでSwigを使用することは、2つの点を除いて、ノードで使用することと基本的に違いはありません。
-
swig.compileFile
代わりに、常にswig.compile
使用しswig.compile
-
extends
、import
およびinclude
正しく使用するにinclude
、templateKey
を指定templateKey
必要があります。
swig.compile(templateString, { filename: templateKey });
つなぐ
<script type='text/javascript" src="//path/to/swig/swig.js">
テンプレートを準備する
var template = swig.compile('<p>{% block content %}{% endblock %}</p>', { filename: 'main' }); var mypage = swig.compile('{% extends "main" %}{% block content %}Oh hey there!{% endblock %}', { filename: 'mypage' });
レンダリング
console.log(mypage.render({}));
そして、我々は得る
<p>Oh hey there!</p>
プロジェクトページ
ドキュメント
Githubプロジェクト