예제
KO

문법

Hwaro는 Jinja2 호환 템플릿 엔진인 Crinja를 사용합니다. 이 페이지는 핵심 문법을 다룹니다.

변수

이중 중괄호로 값을 출력합니다.

{{ page.title }}
{{ site.description }}
{{ content }}

괄호로 묶은 표현식 뒤에도 속성, 인덱스, 호출 접근을 쓸 수 있으므로 필터나 함수 결과에서 바로 필드를 읽을 수 있습니다.

{{ (section.pages | first).title }}
{{ (get_section(path="blog").pages | map(attribute="title") | list)[0] }}

주석

{# This is a comment #}

조건문

{% if page.description %}
<meta name="description" content="{{ page.description }}">
{% endif %}

else와 함께:

{% if page.draft %}
<span class="badge">Draft</span>
{% else %}
<span class="badge">Published</span>
{% endif %}

elif와 함께:

{% if page.section == "blog" %}
<article class="post">{{ content | safe }}</article>
{% elif page.section == "docs" %}
<div class="documentation">{{ content | safe }}</div>
{% else %}
<main>{{ content | safe }}</main>
{% endif %}

표현식 안에서 인라인으로 쓸 수도 있습니다(else 부분은 생략할 수 있으며, 생략하면 빈 값으로 렌더링됩니다).

<a href="{{ item.url }}" class="{{ 'active' if item.url == page.url else '' }}">{{ item.name }}</a>
{% set label = page.title if page.title else "Untitled" %}

a or b는 a가 참이면 a를, 아니면 b를 반환하므로 대체값으로 쓸 수 있습니다: {{ page.description or site.description }}.

반복문

{% for p in section.pages %}
<li><a href="{{ p.url }}">{{ p.title }}</a></li>
{% endfor %}

인덱스와 함께:

{% for tag in page.tags %}
{% if not loop.first %}, {% endif %}
{{ tag }}
{% endfor %}

반복 변수:

변수 설명
loop.index 현재 반복 횟수(1부터 시작)
loop.index0 현재 반복 횟수(0부터 시작)
loop.first 첫 반복에서 true
loop.last 마지막 반복에서 true
loop.length 전체 항목 수({% for x in xs if … %}처럼 걸러낸 반복에서도)
loop.revindex 현재를 포함해 남은 반복 횟수(loop.revindex0: 현재 제외)
loop.previtem / loop.nextitem 이전 / 다음 항목(양 끝에서는 빈 값)
loop.changed(value) value가 직전 호출과 다르면 true
loop.cycle(a, b, …) 주어진 값을 차례로 반복
loop.depth recursive 반복의 중첩 깊이(최상위가 1, loop.depth0은 0부터)

슬라이싱

Jinja2처럼 [start:stop:step]으로 리스트나 문자열의 일부를 꺼냅니다. 각 부분은 생략할 수 있고, 음수는 끝에서부터 세며, 범위를 벗어난 값은 양 끝에 맞춰집니다:

{% for p in section.pages[:5] %}
<li><a href="{{ p.url }}">{{ p.title }}</a></li>
{% endfor %}

{{ page.title[:40] }}
{% for p in section.pages[::-1] %}…{% endfor %}

긴 목록에서 앞의 몇 개만 보여 줄 때는 {% if loop.index <= 5 %}로 나머지를 건너뛰지 말고 슬라이스를 쓰세요. if 방식은 페이지마다 목록 전체를 순회할 수 있습니다.

템플릿 상속

베이스 템플릿

templates/base.html:

<!DOCTYPE html>
<html>
<head>
  <title>{% block title %}{{ site.title }}{% endblock %}</title>
  {{ highlight_css | safe }}
</head>
<body>
  {% block content %}{% endblock %}
  {{ highlight_js | safe }}
</body>
</html>

자식 템플릿

templates/page.html:

{% extends "base.html" %}

{% block title %}{{ page.title }} - {{ site.title }}{% endblock %}

{% block content %}
<article>
  <h1>{{ page.title }}</h1>
  {{ content | safe }}
</article>
{% endblock %}

인클루드

부분 템플릿을 불러옵니다.

{% include "partials/header.html" %}
<main>{{ content | safe }}</main>
{% include "partials/footer.html" %}

매크로

{% macro %}로 재사용할 조각을 정의하고(보통 부분 템플릿에 둡니다), 필요한 곳에서 가져와 씁니다.

templates/partials/macros.html:

{% macro card(p, show_date=true) %}
<a href="{{ p.url }}">{{ p.title }}</a>
{% if show_date and p.date %}<time>{{ p.date }}</time>{% endif %}
{% endmacro %}
{% import "partials/macros.html" as m %}
{% for p in section.pages %}{{ m.card(p) }}{% endfor %}

{% from "partials/macros.html" import card %}
{{ card(page, show_date=false) }}

한 번의 렌더링에서 같은 파일을 여러 번 가져와도 됩니다. 예를 들어 베이스 레이아웃과 그것을 상속하는 자식 템플릿이 각각 가져오거나, 두 이름으로 가져올 수 있습니다. 실제 순환(a.html이 b.html을, b.html이 다시 a.html을 가져오는 경우)만 오류입니다.

변수 설정

변수를 설정합니다.

{% set author = page.authors | first %}
<span>By {{ author }}</span>

필터

파이프 연산자로 값을 변환합니다.

{{ page.title | upper }}
{{ content | safe }}
{{ page.date | date("%B %d, %Y") }}
{{ page.authors | join(", ") }}

전체 필터 목록은 필터를 참고합니다.

테스트

조건을 평가합니다.

{% if page.url is startswith("/blog/") %}
<span>Blog post</span>
{% endif %}

{% if page.description is empty %}
<meta name="description" content="{{ site.description }}">
{% endif %}

테스트는 필터가 아니지만 같은 페이지에 문서화되어 있습니다. 필터 › 테스트를 참고합니다.

공백 제어

마이너스 기호로 공백을 제거합니다. 구분자 옆의 -({%-, -%}, {{-, -}}, {#-, -#})는 Jinja2와 같이 그쪽의 줄바꿈을 포함한 모든 공백을 제거합니다.

{%- if condition -%}
trimmed
{%- endif -%}

raw 블록

Jinja 문법을 그대로 출력합니다.

{% raw %}
{{ this will not be parsed }}
{% endraw %}

연산자

비교

연산자 설명
== 같음
!= 같지 않음
< 미만
> 초과
<= 이하
>= 이상

논리

연산자 설명
and 둘 다 참
or 둘 중 하나라도 참
not 부정
{% if page.section == "blog" and not page.draft %}
<article>{{ content | safe }}</article>
{% endif %}

포함 여부

{% if "tutorial" in page.tags %}
<span class="badge">Tutorial</span>
{% endif %}

자주 쓰는 패턴

활성 내비게이션

<nav>
  <a href="/"{% if page.url == "/" %} class="active"{% endif %}>Home</a>
  <a href="/blog/"{% if page.section == "blog" %} class="active"{% endif %}>Blog</a>
</nav>

조건부 메타 태그

<head>
  {% if page.description %}
  <meta name="description" content="{{ page.description }}">
  {% endif %}
  {{ og_all_tags | safe }}
</head>

섹션별 레이아웃

<body data-section="{{ page.section }}">
  {% if page.section == "docs" %}
  {% include "partials/sidebar.html" %}
  {% endif %}
  
  <main>{{ content | safe }}</main>
</body>

빈 목록 확인과 반복

{% if section.pages %}
<ul>
{% for p in section.pages %}
  <li><a href="{{ p.url }}">{{ p.title }}</a></li>
{% endfor %}
</ul>
{% else %}
<p>No articles yet.</p>
{% endif %}

함께 보기