LoginSignup
14
12

More than 5 years have passed since last update.

nunjucksの使い方

Last updated at Posted at 2017-01-24
  • 試行錯誤中です

nunjucksとは

  • ヌンチャク?
  • mozilla謹製テンプレートライブラリ
  • pythonのjinja2互換
  • テンプレートを事前コンパイルできるのでサーバーで負荷を減らせる
  • includeを使える
  • マクロ定義できる
  • 構造を先に定義して中身をあとで定義する継承機能がある
  • https://mozilla.github.io/nunjucks/
  • https://www.npmjs.com/package/nunjucks

インストール

npm i nunjucks

JS

JSからの呼び出し方

cosnt nunjucks = require('nunjucks');
// テンプレートのコンパイル
const template = nunjucks.compile('{{ hoge }}');
// テンプレートにコンテキストを設定しレンダリング結果を取得
const context = { hoge: 'hello' }
const output = template.render(context)
// 画面表示
console.log(output)

Template

変数表示

{{ variable_name }}

変数設定

{% set username = "joe" %}

コメント

{# Loop through all the users #}

関数呼び出し

{{ func_name() }}

for

{% for value in values %}
{{ value }}
{% endfor %}

空白対策

{% for i in [1,2,3,4,5] -%}
  {{ i }}
{%- endfor %}
12345

空行対策

{%- for value in values -%}
{{ value }}
{%- endfor -%}

if

{% if variable %}
  true
{% endif %}

空行対策

{%- if variable -%}
  true
{%- endif -%}

関数定義

マクロ定義で代行?
クロージャとかできないとmap関数定義できないので不便

マクロ定義

{% macro field(name, value='', type='text') %}
<div class="field">
  <input type="{{ type }}" name="{{ name }}"
         value="{{ value | escape }}" />
</div>
{% endmacro %}

{% macro label(text) %}
<div>
  <label>{{ text }}</label>
</div>
{% endmacro %}

ケツカンマの対処

いい対処方法が見つからないので教えてください
いまのところコンテキスト渡す前に前処理でmap処理しjoinを使える状況にすることで対処

リファレンス

14
12
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
14
12