LoginSignup
1
1

More than 5 years have passed since last update.

jinja2のincludeとmacroをやってみた。

Posted at

jinja2でネストしていく部分を試したので覚書。

でも{{% block %}}の使いどころが理解できない(感覚と逆というか)ので、includemacroをやってみた。

Angularjsのdirectiveでtemplate使う感じ。

本体からincludecontent.htmlを呼んでいる。

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    test
    {% include "./templates/content.html" %}
</body>
</html>

fromでマクロを呼んでいる。

content.html

{%from "./templates/macro.html" import card with context%}

{{card("wowow","#522222")}}

{{card("rerere","#ffcc00")}}


呼ばれるマクロがこれ。

macro.html

{% macro card(text,color) %}
<div style="width:100px;height:200px;background-color:{{color}};">
    {{ text }}
</div>
{% endmacro %}

メインの.pyでreturn template('index.html')で表示されるのだが、ネストしてる部分のパスがファイル名だけだと通らない(TEMPLATE_PATH.append("./templates")してるところに置いてあるのに読まれない)ので、パス指定してあげている。ちゃんとenv設定みたいなのが必要なのかもしれない。

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