これでマクロが1行で呼び出せる。
成果物
問題
前回、マクロの呼出に2行必要だという問題があった。今回、これをHTMLにいれてそれをインクルードすることで1行にした。
コード抜粋
マクロは前回とおなじ。そのマクロを呼び出すだけのhtmlをつくる。
templates/include/header.html
{% import "macro/header.html" as macro %} {{ macro::menu(items=["archive","author","about","blog"]) }}
templates/include/footer.html
{% import "macro/footer.html" as macro %} {{ macro::footer() }}
上記をインクルードする。
templates/index.html templates/page.html
<body> {% include "include/header.html" %} ... {% include "include/footer.html" %} </body>
これで煩雑なマクロのインポートと呼出と名付けを避けることができた。
所感
マクロとインクルードのあわせ技。ここまでやれば、末端のテンプレートが短く書ける。
逆に言えば、ここまでやる必要がある。
さらにいえば、もっと短く書きたかった。以下のように。
{{ "include/header.html" }}
あと、変更するときが面倒そう。
問題
{% extends "base.html" %}
したときbase.html
内でこの技を使うと以下のようなエラーになった。
Error: Failed to render page '/tmp/work/Shell.Zola.Extends.20210802182433/src/ytyaru-zola/content/about/index.md' Reason: Failed to render 'page.html' (error happened in 'base.html'). Reason: Macro namespace `macro` was not found in template `base.html`. Have you maybe forgotten to import it, or misspelled it?
対象環境
- Raspbierry pi 4 Model B
- Raspberry Pi OS buster 10.0 2020-08-20 ※
- bash 5.0.3(1)-release
$ uname -a Linux raspberrypi 5.4.83-v7l+ #1379 SMP Mon Dec 14 13:11:54 GMT 2020 armv7l GNU/Linux