Referencia rápida

Chuleta de Plantillas Mako

Guía de referencia rápida de Mako: sintaxis de plantillas en Python, expresiones, estructuras de control, bloques de código Python, macros def y herencia.

· Publicado

Mako es una biblioteca de plantillas de Python de alto rendimiento que combina velocidad de ejecución con sintaxis familiar de Python y herencia de plantillas.

Sintaxis Básica y Expresiones

Variable x: ${x}
Expression arithmetic: ${x + 1}
HTML-escaped filter: ${x | h}
URL-encoded filter: ${x | u}
Trimmed whitespace: ${x | trim}

Estructuras de Control

Las sentencias de control comienzan con % y deben finalizar con % endif, % endfor, etc.:

% for user in users:
  % if user.is_active:
    <li>${user.name} (Active)</li>
  % else:
    <li>${user.name} (Inactive)</li>
  % endif
% endfor

Código Python Incrustado

Bloques de Python en Tiempo de Renderizado

<%
    greeting = "Hello, " + user.name.upper()
    total_score = sum(user.scores)
%>
<p>${greeting}: ${total_score}</p>

Bloques de Python a Nivel de Módulo

La etiqueta <%! ... %> se ejecuta una sola vez a nivel de módulo cuando la plantilla se compila:

<%!
    import datetime

    def format_date(dt):
        return dt.strftime("%Y-%m-%d")
%>
<p>Today: ${format_date(datetime.date.today())}</p>

Defs (Macros) y Bloques en Bruto

<%def name="render_card(title, body)">
  <div class="card">
    <h3>${title}</h3>
    <p>${body}</p>
  </div>
</%def>

${render_card("Feature", "Card body text")}

<%text filter="h">
  This is a raw block where ${expressions are not evaluated}.
</%text>

<%doc>
  Multi-line template comment
</%doc>

Herencia de Plantillas

Plantilla Base (base.html)

<!doctype html>
<html>
  <head>
    <title><%block name="title">Default Title</%block></title>
  </head>
  <body>
    <header><h1><%block name="header" /></h1></header>
    <main>${self.body()}</main>
  </body>
</html>

Plantilla Hija (child.html)

<%inherit file="base.html" />

<%block name="title">Page Title</%block>
<%block name="header">Welcome to my site</%block>

<p>Este es el contenido principal inyectado en self.body().</p>

Uso de la API de Python

from mako.template import Template

template = Template("Hello, ${name}!")
print(template.render(name="World"))

Referencias

Temas relacionados