빠른 참조

Mako 템플릿 치트시트

Mako 빠른 참조 가이드: Python 템플릿 문법, 표현식, 제어 구조, Python 코드 블록, def 매크로, 템플릿 상속.

· 게시일

Mako는 빠른 실행 속도와 친숙한 Python 구문, 템플릿 상속을 결합한 고성능 Python 템플릿 라이브러리입니다.

기본 문법 및 표현식

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

제어 구조

제어문은 %로 시작하며 % endif, % endfor 등으로 닫아야 합니다:

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

임베디드 Python 코드

렌더링 시점 Python 블록

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

모듈 레벨 Python 블록

<%! ... %> 태그는 템플릿이 Python 코드로 컴파일될 때 모듈 수준에서 한 번만 실행됩니다:

<%!
    import datetime

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

Defs (매크로) 및 Raw 블록

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

템플릿 상속

기본 템플릿 (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>

자식 템플릿 (child.html)

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

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

<p>self.body()에 주입되는 메인 본문 콘텐츠입니다.</p>

Python API 사용법

from mako.template import Template

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

참고 자료

관련 주제