夜猫的小站

pongo2宏的使用

Published on
阅读时间:3分钟597

本文最近一次更新于 1508 个天前,其中的内容很可能已经有所发展或是发生改变。

前言

之前 golang 中使用 pongo2 作为模版框架渲染页面,在使用过程中,需要提取公共页面作为方法传入,依次记录 macro 的使用。

官方例子中宏的使用

<html>
  <head>
    <title>Our admins and users</title>
  </head>
  {% macro user_details(user, is_admin=false) %}
  <div class="user_item">
    <!-- Let's indicate a user's good karma -->
    <h2 {% if (user.karma>
      = 40) || (user.karma > calc_avg_karma(userlist)+5) %} class="karma-good"{%
      endif %}>

      <!-- This will call user.String() automatically if available: -->
      {{ user }}
    </h2>

    <!-- Will print a human-readable time duration like "3 weeks ago" -->
    <p>This user registered {{ user.register_date|naturaltime }}.</p>

    <!-- Let's allow the users to write down their biography using markdown;
             we will only show the first 15 words as a preview -->
    <p>The user's biography:</p>
    <p>
      {{ user.biography|markdown|truncatewords_html:15 }}
      <a href="/user/{{ user.id }}/">read more</a>
    </p>

    {% if is_admin %}
    <p>This user is an admin!</p>
    {% endif %}
  </div>
  {% endmacro %}

  <body>
    <h1>Our admins</h1>
    {% for admin in adminlist %} {{ user_details(admin, true) }} {% endfor %}

    <h1>Our members</h1>
    {% for user in userlist %} {{ user_details(user) }} {% endfor %}
  </body>
</html>

其中macro user_details(user, is_admin=false)就是对宏的定义。 但是大部分情况下,我们定义的macro是作为独立文件存储,而不是类似官方文档中与页面在同一个文件。

macro作为独立文件引入

查询了下官方文档,发现还是有引入方式的说明文件的,不过是在测试代码中。

定义宏文件 macros/user.html

比如我们把宏文件定义为```user.html``放在macros目录下

  • user.html的内容如下
  {% macro user_details(user, is_admin=false) export%}
  <div class="user_item">
    <!-- Let's indicate a user's good karma -->
    <h2 {% if (user.karma>
      = 40) || (user.karma > calc_avg_karma(userlist)+5) %} class="karma-good"{%
      endif %}>

      <!-- This will call user.String() automatically if available: -->
      {{ user }}
    </h2>

    <!-- Will print a human-readable time duration like "3 weeks ago" -->
    <p>This user registered {{ user.register_date|naturaltime }}.</p>

    <!-- Let's allow the users to write down their biography using markdown;
             we will only show the first 15 words as a preview -->
    <p>The user's biography:</p>
    <p>
      {{ user.biography|markdown|truncatewords_html:15 }}
      <a href="/user/{{ user.id }}/">read more</a>
    </p>

    {% if is_admin %}
    <p>This user is an admin!</p>
    {% endif %}
  </div>
  {% endmacro %}

引入宏文件 macros/user.html

<html>
  <head>
    <title>Our admins and users</title>
  </head>
  <body>
    {% import "macros/user.html" article_details  %}
    <h1>Our admins</h1>
    {% for admin in adminlist %} {{ user_details(admin, true) }} {% endfor %}

    <h1>Our members</h1>
    {% for user in userlist %} {{ user_details(user) }} {% endfor %}
  </body>
</html>

可以发现其实就是在定义macro文件是在方法上({% macro user_details(user, is_admin=false) export%})增加一个export,之后在目标模版中使用import关键字引入。

更多相关资料