自定义小部件:相当于 Jinja2 或 Django 模板中 Mako 的 <%def>

Custom widgets: The equivalent of Mako's <%def> in Jinja2 or Django templates

我非常精通 Mako,但从未真正使用过 Jinja 或 Django 模板。

Mako <%def name="..."> 定义的 Jinja/Django 是什么?

以下是我的实际用例的简化示例。我需要定义一个简单的 table 并在页面上重复使用它:

<%def name="temperature_table(north, east, south, west)">
    <table>
        <tr>
            <td>North:</td>
            <td>${north}</td>
        </tr>
        <tr>
            <td>East:</td>
            <td>${east}</td>
        </tr>
        <tr>
            <td>South:</td>
            <td>${south}</td>
        </tr>
        <tr>
            <td>West:</td>
            <td>${west}</td>
        </tr>
    </table>
</%def>

<h2>Morning</h2>
${weather_table(20, 21, 22, 23)}

<h2>Afternoon</h2>
${weather_table(22, 22, 25, 24)}

<h2>Night</h2>
${weather_table(17, 16, 17, 18)}

根据我从各种文章中收集到的信息, 似乎在 Jinja/Django 中用于此目的。但是块甚至会向简单的模板引入继承,其中自定义小部件就足够了。其他作者建议创建一个自定义标记,但在我看来,这将需要编写自定义解析、呈现,甚至可能需要自定义缓存管理功能。我错过了什么吗?

您可以为此使用 macro

如手册中所述:

Macros are comparable with functions in regular programming languages. They are useful to put often used idioms into reusable functions to not repeat yourself (“DRY”).

来源:https://jinja.palletsprojects.com/en/3.0.x/templates/#macros

所以,给定:

{% macro weather_table(north, east, south, west) -%}
  <table>
      <tr>
          <td>North:</td>
          <td>{{ north }}</td>
      </tr>
      <tr>
          <td>East:</td>
          <td>{{ east }}</td>
      </tr>
      <tr>
          <td>South:</td>
          <td>{{ south }}</td>
      </tr>
      <tr>
          <td>West:</td>
          <td>{{ west }}</td>
      </tr>
  </table>
{%- endmacro %}

<h2>Morning</h2>
{{ weather_table(20, 21, 22, 23) }}

<h2>Afternoon</h2>
{{ weather_table(22, 22, 25, 24) }}

<h2>Night</h2>
{{ weather_table(17, 16, 17, 18) }}

它呈现您期望的表格。

<h2>Morning</h2>
<table>
  <tr>
    <td>North:</td>
    <td>20</td>
  </tr>
  <tr>
    <td>East:</td>
    <td>21</td>
  </tr>
  <tr>
    <td>South:</td>
    <td>22</td>
  </tr>
  <tr>
    <td>West:</td>
    <td>23</td>
  </tr>
</table>

<h2>Afternoon</h2>
<table>
  <tr>
    <td>North:</td>
    <td>22</td>
  </tr>
  <tr>
    <td>East:</td>
    <td>22</td>
  </tr>
  <tr>
    <td>South:</td>
    <td>25</td>
  </tr>
  <tr>
    <td>West:</td>
    <td>24</td>
  </tr>
</table>

<h2>Night</h2>
<table>
  <tr>
    <td>North:</td>
    <td>17</td>
  </tr>
  <tr>
    <td>East:</td>
    <td>16</td>
  </tr>
  <tr>
    <td>South:</td>
    <td>17</td>
  </tr>
  <tr>
    <td>West:</td>
    <td>18</td>
  </tr>
</table>